2

I am working on a small home automation project using raspberry pi (OS -Raspbian).

I want to know how to add more than one crontab file using python-crontab module without replacing the previous entries in crontab -e?

I want to programatically (without manually going to crontab -e and adding the files there) schedule two python scripts - first script executes after every 5 minute and another executes after every 2 min.

I was successfully able to schedule first script using python-crontab module but when I scheduled second script, it replaced the first one in crontab -e. So how to schedule the new crontab file without replacing the previous one ?

If there is another way of crontab scheduling please do suggest with an example code :)

Note:- I want to schedule python scripts in crontab using python scripting only not manually adding the files at crontab -e.

Thomas Dickey
  • 76,765
user3647026
  • 21
  • 1
  • 2

3 Answers3

5

If you want to write a script to add entries in cron (without using the text editor via crontab -e), it would be something like:

  • run crontab -l to a temporary file
  • check if your latest command is already in the file. If so, stop.
  • append the latest command to the temporary file
  • run crontab with the temporary file as a parameter, to replace the scheduled commands

For reference:

Thomas Dickey
  • 76,765
0

Since crontabs are text files after all, why not just append text?

with open("/var/spool/cron/crontabs/john", "a") as ctfile:
    ctfile.write("1 0 * * 3 /path/to/newcommand --option")
FelixJN
  • 13,566
-2

crontab -e is actually a file where you list all of your cronjobs.

When you type crontab -e you will get list of previous cronjobs and tildas (~).

Press the insert button on your keyboard to switch between modes and press enter at the end of your last cronjob.

It will erase the tilda and you can write your new cronjob here.

To exit insert mode press escape and enter :wq! to save changes.

  • 1
    crontab -e is not a file, its a command. The behaviour you describe reflects that when the default editor is 'vi' (or a derivative) however many Linux distributions now default to nano as the default editor. Further the OP asked how to make changes "programatically" while you have have described an interactive approach. – symcbean Jun 23 '23 at 12:04