Search code examples
pythondjangocron

Cron parser and validation in python


I am currently running a django web app in python where I store cron entries entered by the user into a database. I was wondering if there are any python libraries/packages that will validate these entries before I store them into the database. By validate I mean correct syntax as well as the correct range (ex: month cannot be 15). Does anyone have any suggestions? Thanks!


Solution

  • The Croniter package seems like it may get what you need. Example from the docs:

    >>> from croniter import croniter
    >>> from datetime import datetime
    >>> base = datetime(2010, 1, 25, 4, 46)
    >>> iter = croniter('*/5 * * * *', base)  # every 5 minites
    >>> print iter.get_next(datetime)   # 2010-01-25 04:50:00
    >>> print iter.get_next(datetime)   # 2010-01-25 04:55:00
    >>> print iter.get_next(datetime)   # 2010-01-25 05:00:00
    >>>
    >>> iter = croniter('2 4 * * mon,fri', base)  # 04:02 on every Monday and Friday
    >>> print iter.get_next(datetime)   # 2010-01-26 04:02:00
    >>> print iter.get_next(datetime)   # 2010-01-30 04:02:00
    >>> print iter.get_next(datetime)   # 2010-02-02 04:02:00
    

    Per the code, it also appears to do validation on the entered format. Likely that you came across this already, but just in case :)