Git Product home page Git Product logo

cron-validator's Introduction

Cron Validator

Build Status Coverage Status

Features

  • Validate unix cron expression
  • Match unit cron expression with specific datetime
  • Generate match datetime between two datetime
  • Schedule tasks

Install

pip install cron-validator

Run Tests

1. Install test requirements

pip install -r requirements/test.txt

2. Run tests (with coverage if wished)

pytest --cov=. test/

Sample

1. Validate unix cron expression

from cron_validator import CronValidator

assert CronValidator.parse('* * * * *') is not None # valid
assert CronValidator.parse('*/3 * * * *') is not None # valid
assert CronValidator.parse('*/61 * * * *') is None # invalid

2. Match unit cron expression with specific datetime

from cron_validator import CronValidator
from cron_validator.util import str_to_datetime

dt_str = '2019-04-23 1:00'
dt = str_to_datetime(dt_str)

assert CronValidator.match_datetime("* * * * *", dt)
assert CronValidator.match_datetime("* * * 4 *", dt)
assert CronValidator.match_datetime("* * * 5 *", dt) is False
assert CronValidator.match_datetime("* * * 1-5 *", dt)
assert CronValidator.match_datetime("* * * 1-3 *", dt) is False
assert CronValidator.match_datetime("* * * 1/5 *", dt) is False
assert CronValidator.match_datetime("* * * * *", dt)
assert CronValidator.match_datetime("0 * * * *", dt)
assert CronValidator.match_datetime("0-30 * * * *", dt)
assert CronValidator.match_datetime("0/30 * * * *", dt)

3. Generate match datetime between two datetime

from cron_validator import CronValidator
from cron_validator.util import str_to_datetime


from_str = '2019-04-22 00:00'
to_str = '2019-04-23 23:59'

for dt in CronValidator.get_execution_time("0 0 * * *",
from_dt=str_to_datetime(from_str), to_dt=str_to_datetime(to_str)):
    print(dt)

# Output:
# 2019-04-22 00:00:00+00:00
# 2019-04-23 00:00:00+00:00

4. Use scheduler for repetitive task

from cron_validator import CronScheduler

cron_string = "*/1 * * * *"
scheduler = CronScheduler(cron_string)

while True:
    if scheduler.time_for_execution():
        # Get's called every full minute (excluding first iteration)
        print("Now is the next scheduled time.")

5. Use extended cron rules based on AWS EventBridge rules (from v1.0.6)

The cron validator supports partially extended rules based on the Amazon EvenBridge rule set. More info.

Currently we support:

  • 'L' for day of the month and day of the week
  • 'W' for day of the week.
from cron_validator import CronValidator
from cron_validator.util import str_to_datetime
from cron_validator.regexes import Version

dt_str = '2023-04-28 1:00'
dt = str_to_datetime(dt_str)

assert CronValidator.match_datetime("* * * * 30W", dt, version=Version.EB)
assert CronValidator.match_datetime("* * * * 5L", dt, version=Version.EB)

dt_str = "2022-02-28 1:00"
dt = str_to_datetime(dt_str)
assert CronValidator.match_datetime("* * L * *", dt, version=Version.EB)

License

This project is licensed under the MIT License - see the LICENSE.txt file for details

cron-validator's People

Contributors

kaka2507 avatar dprosperino avatar robinje avatar mhrmsn avatar wyleung avatar mmasztalerczuk avatar sindrig avatar

Stargazers

Isaiah Eichen avatar Ryan Prasad avatar  avatar Thiago Brasil avatar Sergey Mezentsev avatar  avatar Sylvain Hellegouarch avatar  avatar  avatar Luke Simmons avatar Sasha avatar Felix avatar Arvin avatar  avatar Henshal B avatar Bryan A. S. avatar Daniel Tharp avatar Nick Demianchuk  avatar  avatar Dmitry Burnaev avatar Thierry BOULOGNE avatar Ying Wang avatar Alejagapatrick avatar Panda avatar

Watchers

James Cloos avatar  avatar

cron-validator's Issues

Month matching in cron expression

Hi,

I want to use the month field in cron expression but it seems there is a problem with it.

I make multiple test with get_execution_time. January month match with 1 and so one like we can see in most cron implementation. But I can build a expression with 12 (like 0 11 1 12 *) in the fourth field. There is a regex in regexes.py that limit this field from 0 to 11.

The solution for me is to correct the regex in month_re for matching "12" too. Perhaps max_value_map needs to be changed too.

Did I not understand how to build the expressions or is it a bug?

Wrong validation

I want to run cron at every 5th minute past every hour from 11pm through 11am. And this is the schedule */5 0-11,23 * * *. When I run this code

from cron_validator import CronValidator
CronValidator.parse('*/5 0-11,23 * * *')

I got error

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.9/site-packages/cron_validator/validator.py", line 23, in parse
    raise ValueError(f"Invalid expression part {i}")
ValueError: Invalid expression part 1

I think its a bug.

I tried using crontab.guru and this lib in nodejs https://github.com/GuillaumeRochat/cron-validator it all valid.

I'm using:

  • Python 3.9.15
  • cron-validator==1.0.8

Incorrect sample code in README

Hi,

In the README, here: https://github.com/vcoder4c/cron-validator/blob/master/README.md#sample

There is this bit of sample code for validating a cron expression:

from cron_validator import CronValidator

assert CronValidator.parse('* * * * *') is not None # valid
assert CronValidator.parse('*/3 * * * *') is not None # valid
assert CronValidator.parse('*/61 * * * *') is None # invalid

This is not what it actually does:

CronValidator.parse('* * * * *')  is not None  => True
CronValidator.parse('*/3 * * * *') is not None => True
CronValidator.parse('*/61 * * * *') => ValueError: Invalid expression part 0

I.E. passing an invalid value to CronValidator.parse makes it raise a ValueError, it doesn't return None.

I don't mind the ValueError, I just didn't understand why the described behaviour and actual behaviour were different.

Also:

CronValidator.parse(0) => AttributeError: 'int' object has no attribute 'split'  # Should be a ValueError?

Bug for Complicated Cron Jobs

Hey!

While building the scheduler, I found that one of my test did not pass and I investigated it a bit.
I don't know where it fails, but I know what does fail:

Taking this cron job description: "*/5 1-6 * 3 2-4"

According to crontab.guru and cronhub.io the next scheduled dates are:
2021-03-02 01:00:00, 2021-03-02 01:05:00, 2021-03-02 01:10:00, 2021-03-02 01:15:00, 2021-03-02 01:20:00

However, when running this code:

exec_time = CronValidator.get_execution_time(expression="*/5 1-6 * 3 2-4", from_dt=datetime.datetime(year=2021, month=2, day=24, hour=9, minute=21, second=46), to_dt=None)
for i in range(10):
    print(next(exec_time))

The output is:
2021-03-03 01:00:00
2021-03-03 01:05:00
2021-03-03 01:10:00
2021-03-03 01:15:00
2021-03-03 01:20:00
2021-03-03 01:25:00
2021-03-03 01:30:00
2021-03-03 01:35:00
2021-03-03 01:40:00
2021-03-03 01:45:00

So it seems, it gets the day wrong.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.