Sunday, May 20, 2018

Kubernetes - Cron Job

Similar to Jobs kubernetes does have an option to schedule jobs. Kubernetes lets us to use cron job to perform a finite, time related tasks that run once or repeatedly at a time that we specify. Cron jobs can be used for automatic tasks that run on specific time, such as backups , reporting and sending emails.

Cron jobs are based on jobs. they use Job objects to complete their tasks. cron Job creates a job object about once per execution time of the schedule. Cron jobs are created, managed, scaled and deleted in the same way as jobs

lets create a simple cron job using,
[root@manja17-I13330 kubenetes-config]# cat scheduled-jobs.yml
apiVersion: batch/v1beta1
kind: CronJob
metadata:
 name: testing-service
spec:
 schedule: "*/1 * * * *"
 jobTemplate:
   spec:
     template:
       spec:
         containers:
           - name: counter
             image: centos:7
             command:
                - "bin/bash"
                - "-c"
                - "for i in 3 2 1 ; do echo $i ; done"

         restartPolicy: OnFailure

The main element in the above config file is the schedule element.i am creating a pod that will be executed every 1 minute. This generally creates a pod which further creates a container called "counter" that runs a bash for loop.

The pod will be created every 1 minute and run until job is completed.
[root@manja17-I13330 kubenetes-config]# kubectl get jobs --watch
NAME                          DESIRED SUCCESSFUL AGE
testing-service-1526757000   1 0 3s
testing-service-1526757000   1 1 21s
testing-service-1526757060   1 0 0s
testing-service-1526757060   1 0 0s
testing-service-1526757060   1 1 3s

We can see that a pod is being created for every 1 minute which has a container "counter" running the bash for loop. We can get the cron jobs available using,
[root@manja17-I13330 kubenetes-config]# kubectl get cronjobs
NAME               SCHEDULE SUSPEND   ACTIVE LAST SCHEDULE  AGE
testing-service   */1 * * * * False      0 50s   2m

Lets see that the pods are running are not, using
[root@manja17-I13330 kubenetes-config]# kubectl get pods
NAME                                READY STATUS RESTARTS AGE
testing-service-1526757000-gh8bb   0/1 Completed 0 2m
testing-service-1526757060-2t67m   0/1 Completed 0 1m
testing-service-1526757120-z72t6    0/1 Completed 0 25s

Check the logs for each pod as,
[root@manja17-I13330 kubenetes-config]# kubectl logs
testing-service-1526757120-z72t6
3
2
1

[root@manja17-I13330 kubenetes-config]# kubectl logs testing-service-1526757060-2t67m
3
2
1

More to come , happy learning :-)

No comments :

Post a Comment