dragonmantank / cron-expression

CRON for PHP: Calculate the next or previous run date and determine if a CRON expression is due
MIT License
4.57k stars 124 forks source link

Q: Use cron-expression to rotate log files #170

Closed theking2 closed 11 months ago

theking2 commented 1 year ago

in \cronExpression I see interfaces for ::isDue() ::getPreviousRunDate() and ::getNextRunDate(). How would I use these to find out if a log file needs to be rotated? Would I need something else like a state variable $lastRunDate?

dragonmantank commented 1 year ago

Rotating the logs itself would be outside of the logic of this library, but you could use it to trigger whatever logic you want. You would pick a time of day that you would want to run the check and come up with an appropriate cron expression, and then the library can tell you if the current time matches your expression.

For example, you could use something like 0 * * * * to run a script every hour to see if a log file has reached a given file size, and then rotate the file.

You could also do something like 0 0 * * * and run a script to rotate the log file at midnight just because.

You wouldn't need to store any state since the trigger won't ever be something based on a past or future run date. Even if it's "time based" like just rotate every hour, day, whatever, you'd just trigger based on the expression.

theking2 commented 1 year ago

It would only work if the frequency calling it would be higher than the cron frequency. If I'm not mistaken crontab on unix uses a state file (/var/spool/crontab ?). I've found a work around by indeed store the last rotation in the mtime of a file.