Number of occurrences of a generic recurring event between two dates

297 Views Asked by At

Intro

Cron is a very common tool in computer science, which allows to schedule an event given a generic pattern written in a file called crontab. I'm researching on an algorithm to calculate the number of times a given generic recurring event is going to happen between two given dates (timestamps)

Problem

  • Given a generic starting date
    • Unix Timestamp 636015272
    • Date: Tue, 26-02-1990 GMT 6:54:32 am)
  • Given a generic end date
    • Unix Timestamp 1542749251:
    • Date: Tue 20-11-2018 GMT 9:27:31 pm)
  • Given a generic recurring event expression(Crontab)

How many times the recurring event has been triggered between both dates?

Extra comments

  • The solution must be O(1), by just using calculations between the two given timestamps. This means: it is not valid to recursively increase or decrease a time interval interval to check if the solution is on bounds

  • Crontab expressions are expressed in UTC, cosiderations such as daylight saving can be ignored

  • Extra simplifications, such as removing day of the week can also be considered


So far, the problem seems duable by using modular arithmetics and handling many different inputs using particular logic for each case. However, the complexity of handling particularly cases gets really high. It would be nice having some models, or general algebraic functions to make the calculation.

1

There are 1 best solutions below

0
On

Let us omit the 'day of week' field for now, and only focus on year, month, dayofmonth, hours, and minutes.

You can decompose the number of cron runs in three different time intervals: the first day, the last day, and the in-between days. The first and the last day are independent on the interval, so any method gives you the $\mathcal{O}(1)$ ressult.

Let us therefore focus on the number of in-between days. To count those, you first count the number of Januarys, Februarys in non-leap years, Februarys in leap years, Marches, etc. Converting those month counts to days is trivial, and you multiplying that with the number of hours at which it runs and the number of minutes at which it runs to get the total number of runs on in-between days.