Search code examples
kubernetescronkubernetes-cronjob

I want to restart my kubernates pods after every 21 days


I want to restart my Kubernetes pods after every 21 days I want probably a crone job that can do that. That pod should be able to restart pods from all of my deployments. I don't want to write any extra script for that is that possible ? Thanks you .


Solution

  • If you want it to run every 21 days, no matter the day of month, then cron job doesn't support a simple, direct translation of that requirement and most other similar scheduling systems.

    In that specific case you'd have to track the days yourself and calculate the next day it should run at by adding 21 days to the current date whenever the function runs.

    My suggestion is : if you want it to run at 00:00 every 21st day of the month:

    Cron Job schedule is : 0 0 21 * * (at 00:00 on day-of-month 21).
    

    Output :

    enter image description here

    If you want it to run at 12:00 every 21st day of the month:

    Cron Job schedule is  : 0 12 21 * * (at 12:00 on day-of-month 21).
    

    Output :

    enter image description here

    Or else

    If you want to add the 21 days yourself, you can refer and use setInterval to schedule a function to run at a specific time as below :

    const waitSeconds = 1814400; // 21 days
    
    function scheduledFunction() {
      // Do something
    }
    
    // Run now
    scheduledFunction();
    
    // Run every 21 days
    setInterval(scheduledFunction, waitSeconds);
    

    For more information Refer this SO Link to how to schedule Pod restart.