Search code examples
pythoncron

How to iterate over all crontab jobs and print the jobs' schedules, commands and comments


I've got the following .py code

from crontab import CronTab
...
searchResultsList = cron.find_command('bar')
for eachJob in searchResultsList:
    print("Found this job", eachJob.command, eachJob.comment)

When I eyeball the crontab -l, I can see the .py is finding the jobs it should, but how can I get the .py program to access the schedule rules (*/10 2-4 0 4 *) of each job? Something like eachJob.rules or eachJob.schedule.


Solution

  • Problem

    Access cron expression (schedule) of each crontab job.

    Solution

    There are multiple solutions depending on what you want to do with the cron expression next.

    1. Outside of Python, with grep

    crontab -l | grep 'bar'

    and the result would be something like this:

    0 10 * * * bash bar.sh
    0 23 * * * bash bar.sh
    

    2. Within Python, sticking with the python-crontab package

    2.1 You could print eachJob when you iterate through searchResultsList:
    for eachJob in searchResultsList:
        print("Found this job", eachJob)
    

    and the result would be something like this:

    Found this job  0 10 * * * curl -X GET https://maker.ifttt.com/trigger/event/with/key
    Found this job  0 23 * * * curl -X GET https://maker.ifttt.com/trigger/event/with/key
    
    2.2 If you would like to access the schedule rules alone with 'python-crontab', according to Get attribute from existing cron (#72) · Issues · Martin Owens / python-crontab · GitLab, you can do:
    for eachJob in searchResultsList:
        print(eachJob[0], eachJob[1], eachJob[2], eachJob[3], eachJob[4])
    

    and the result would be something like:

    0 10 * * *
    0 23 * * *