crontab
The `crontab` library (from the `josiahcarlson/parse-crontab` project) is a Python package designed to parse crontab schedule entries and determine the next execution time. It calculates delays in seconds until a scheduled event. The current version is 1.0.5, with sporadic but active development and releases.
Warnings
- gotcha Potential confusion with `python-crontab` library. The `crontab` (PyPI slug) library, backed by `josiahcarlson/parse-crontab` on GitHub, focuses on parsing cron expressions and calculating next run times. Another popular library, `python-crontab` (PyPI slug), provides similar `from crontab import CronTab` imports but is designed for managing system crontab entries. Ensure you've installed and are importing the library that matches your intended use (parsing vs. system management).
- gotcha Unsupported cron expression symbols and field limits. This library (`crontab` by josiahcarlson) explicitly states that 'W' and '#' symbols are not supported. It also only accepts 5-7 value crontab entries, which are internally 'mangled' to 7 values (seconds-year) as necessary.
- gotcha Scripts executed by system cron jobs often fail due to differences in the execution environment (e.g., `PATH`, current working directory, user permissions, virtual environment activation) compared to manual execution. This is a general `cron` issue but critical for scripts scheduled based on this library's output.
Install
-
pip install crontab
Imports
- CronTab
from crontab import CronTab
Quickstart
from crontab import CronTab
from datetime import datetime
# Define a crontab entry for 25 minutes past the hour, every hour
entry = CronTab('25 * * * *')
# Get the next scheduled execution time from now
now = datetime.now()
next_run_time = now + timedelta(seconds=entry.next(now))
print(f"Current time: {now}")
print(f"Next run for '25 * * * *' will be at: {next_run_time}")
# Example with a specific start time
some_past_time = datetime(2023, 1, 1, 10, 15, 0)
next_from_past = some_past_time + timedelta(seconds=entry.next(some_past_time))
print(f"Next run from {some_past_time} would be at: {next_from_past}")