Search code examples
node.jsexpressscheduled-tasksgoogle-kubernetes-engine

Running cronjob in NodeJS express triggers 3 times hosted on Google Kubernetes Engine with 3 nodes. How to run a cronjob within a node?


I have a scenario where I am sending email in every 1 days with using node-cron library in nodejs. The server is hosted in GKE with three nodes. But I am getting 3 emails each day, I believe from 3 different nodes running the same scheduled function. How can I overcome this so I get email from only one node?

I tried using cluster package

if(cluster.isMaster){
   initScheduleFunctions()
}

in my index.js.


Solution

  • So your current deployment has 3 replicas:

    apiVersion: apps/v1
    kind: Deployment
    metadata: null
    name: backend-deploy
    spec: null
    replicas: 3
    selector: null
    matchLabels: null
    app: app
    template:
      metadata: null
      labels:
        app: app
      spec:
        containers:
          - image: 'gcr.io/vektor-dev-351106/vektor-pm-be:latest'
            name: vektor-be
            imagePullPolicy: Always
            ports:
              - containerPort: 4000
    

    If you want to continue running your job as a Deployment, just modify replicas to 1:

    apiVersion: apps/v1
    kind: Deployment
    metadata: null
    name: backend-deploy
    spec: null
    replicas: 1
    selector: null
    matchLabels: null
    app: app
    template:
      metadata: null
      labels:
        app: app
      spec:
        containers:
          - image: 'gcr.io/vektor-dev-351106/vektor-pm-be:latest'
            name: vektor-be
            imagePullPolicy: Always
            ports:
              - containerPort: 4000