Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to run a cronjob every 10 seconds in kubernetes?

"I just want to run a cronjob in Kubernetes in every 10 seconds. what would be the imperative command for that?"

like image 604
Ishara Nuwan Avatar asked Dec 22 '22 17:12

Ishara Nuwan


1 Answers

You can’t use CronJob kubernetes object for running less than 1 minute. You might be using the wrong tool for a process that has to run so often. https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/

Create an infinite loop on a Deployment (daemonize it)

You’ll need to use a bash formula (or whatever programming language you like best, Go, Java, Python or Ruby) to make an infinite loop and sleep 10 seconds per each execution inside a Deployment. Here an example with bash/sh:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: cronjob-deployment
  labels:
    app: cronjob
spec:
  replicas: 1
  selector:
    matchLabels:
      app: cronjob
  template:
    metadata:
      labels:
        app: cronjob
    spec:
      containers:
      - name: cronjob
        image: busybox
        args:
        - /bin/sh
        - -c
        - while true; do echo call ./script.sh here; sleep 10; done

Create 1 CronJob with several containers

If you still want to use CronJobs you can do it with 6 containers inside the definition. One without delay, and the others with 10, 20, 30, 40 and 50 seconds of delay.

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: hello
spec:
  schedule: "*/1 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: no_delay
            image: busybox
            args:
            - /bin/sh
            - -c
            - echo call ./script.sh here
          - name: 10_seconds
            image: busybox
            args:
            - /bin/sh
            - -c
            - sleep 10; echo call ./script.sh here
          - name: 20_seconds
            image: busybox
            args:
            - /bin/sh
            - -c
            - sleep 20; echo call ./script.sh here
          - name: 30_seconds
            image: busybox
            args:
            - /bin/sh
            - -c
            - sleep 30; echo call ./script.sh here
          - name: 40_seconds
            image: busybox
            args:
            - /bin/sh
            - -c
            - sleep 40; echo call ./script.sh here
          - name: 50_seconds
            image: busybox
            args:
            - /bin/sh
            - -c
            - sleep 50; echo call ./script.sh here
          restartPolicy: OnFailure

Of course, one of the problems you might encounter is that your process might be overlapped (runned concurrently at the same time). This will depend on the amount of seconds your process needs to run, and the time kubernetes needs to schedule and create a container.

like image 159
morhook Avatar answered Jan 04 '23 02:01

morhook