Search code examples
pythoncron

python-crontab: find existing cron jobs is giving wrong result


With my python script below, I wanted to check if a cron job is defined in my linux (centOS 7.5) server, and if it doesn't exist, I will add one by using python-crontab module.. It was working well until I gave CRONTAB -R to delete existing cron jobs and when I re-execute my python script, it is saying cronjob exists even after they were removed using crontab -r..

import os
from crontab import CronTab
cron = CronTab(user="ansible")
job = cron.new(command='echo hello_world')
job.minute.every(1)
basic_command = "* * * * * echo hello_world"
basic_iter = cron.find_command("hello_world")

for item in basic_iter:
    if str(item) == basic_command:
        print("crontab job already exist", item)
        break
    else:
        job.enable()
        cron.write()
        print("cronjob does not exist and added successfully.. please see \"crontab -l\" ")
        break

list of current cron jobs

[ansible@node1 ansible]$ crontab -l
no crontab for ansible

[user - ansible]

python code results:

crontab job already exist * * * * * echo hello_world

It was working until I removed cron jobs using command crontab -r and now my python output is saying that cron job already exists.

Not sure what my mistake was - please help.. (or if there is any better way to find cron jobs in local user, please help with that).


Solution

  • The problem is that you have initialized a new Cron job before checking if it exists. You assumed that Cron.find_command() is only identifying enabled cron jobs. But it also identifies cronjobs that are created, but not enabled yet.

    So, you have to check if the cronjob exists before creating a new job. Then, if it does not exist, you can create a new cron job and enable it. You can try the below code:

    import os
    from crontab import CronTab
    cron = CronTab("ansible")
    basic_command = "* * * * * echo hello_world"
    basic_iter = cron.find_command("hello_world")
    exsist=False
    for item in basic_iter:
        if str(item) == basic_command:
            print("crontab job already exist", item)
            exsist=True
            break
    
    if not exsist:
        job = cron.new(command='echo hello_world')
        job.minute.every(1)
        job.enable()
        cron.write()
        print("cronjob does not exist and added successfully.. please see \"crontab -l\" ")