Search code examples
pythonlinuxpython-3.xcroncron-task

How to append crontab entries using python-crontab module?


I would like to ask for help with the python-crontab module. I have a simple shell script to record an internet radio stream using the curl command. I want to schedule recordings ahead by scheduling them in a crontab. I found the python-crontab module that alows me to write directly to crontab. But each time I schedule a new recording the older crontab entry is over-written. Is it possible to write persistant crontab entries using the python-crontab?

I simplified my code to demonstrate my problem:


from crontab import CronTab

def get_recording_parameters(Min,Hour,day,month,job_number):
    radio_cron = CronTab()
    cmd = "sh /home/pifik/Documents/record_radio.sh"
    cron_job = radio_cron.new(cmd, comment='job_'+str(job_number))
    cron_job.setall(Min, Hour, day, month, None)   
    radio_cron.write()

If I run it with the following parameters: get_recording_parameters(0,22,23,12,1), and check the crontab in Terminal with the crontab -l command I get 0 22 23 12 * sh /home/pifik/Documents/record_radio.sh # job_1. If I run it again with different parameters, for example: get_recording_parameters(10,23,25,12,2) and check the crontab with crontab -l I get 10 23 25 12 * sh /home/pifik/Documents/record_radio.sh # job_2, the job 1 is overwritten.

I tried to change the 3rd line of code to radio_cron = CronTab(tabfile='/home/pifik/Documents/filename.tab') and it helps that all new entries are appended in the filename.tab but nothing is written to the crontab. I am running Ubuntu 14.04 and Python 3.4.3.


Solution

  • The issue is that you haven't specified any user or filename for CronTab to load from. So it doesn't. The bug is that it writes out the empty crontab to the user by default, even if you don't specify the user.

    The existing documentation says:

    from crontab import CronTab
    empty_cron    = CronTab()
    my_user_cron  = CronTab(user=True)
    users_cron    = CronTab(user='username')
    

    Which is correct in that you're making an empty crontab. So I've gone ahead and committed a fix and a test to make sure it causes an error if you try and write an empty_cron without specifying the user or filename.

    Please add user=True to your code to make it work as you expect.