Search code examples
pythoncentoscroncron-task

Python Crontab Overwrites the previous job instead of creating a new one


Pasting my python code below:

from crontab import CronTab

tab = CronTab()
cmd1 = 'actual command'

cron_job = tab.new(cmd)
cron_job.minute.every(1)

cron_job.enable()
tab.write_to_user(user=True)

I am setting these cronjob based on some user input on an app. So overtime a user clicks submit, I want to create a new cronjob under the same crontab file (since its a webapp, it runs under the context of a standard user).

But it seems every time a user clicks submit, my crontab overwrites the previous task. Am I missing something here?


Solution

  • The way you are recreating the tab variable on each request does not append to the crontab in question; it overwrites it.

    If you pass user=True to the CronTab constructor you will be able to append to the existing crontab:

    from crontab import CronTab
    
    tab = CronTab(user=True)
    cmd1 = 'echo Hello'
    cmd2 = 'echo CronTab'
    
    job1 = tab.new(cmd1)
    job1.minute.every(1)
    job1.enable()
    
    job2 = tab.new(cmd2)
    job2.hour.every(1)
    job2.enable()
    
    print list(tab.commands)  # ['echo Hello', 'echo CronTab']
    
    # Explicitly specify we want the user's crontab:
    tab2 = CronTab(user=True)
    
    print list(tab2.commands)  # ['echo Hello', 'echo CronTab']