WARNING: Cron jobs are not the best solution
You have probably already used cron jobs, as they are commonly used in scheduled processes.
A cron expression is a string that represents a schedule for executing a specific task or command at predefined times.
Example:
0 12 * * MON
0 (Minute): The task will run at the 0th minute (top of the hour).
12 (Hour): The task will run at 12 PM (noon).
* (Day of the Month): The task will run every day of the month.
* (Month): The task will run every month.
MON (Day of the Week): The task will run on Monday.
This is a simple example of a cron expression. It is very powerful; however, it can be hard to understand and manage when we have many microservices that depends on specific domain events.
To solve that, let’s see the idea of Passage of Time Event, inspired by Matthias Verraes post.
Passage of Time Event
The passage of time event is a Domain Event. The Domain Event is a specific point in time when something relevant to the business occurred.
An event is something that has happened in the past. A domain event is, something that happened in the domain that you want other parts of the same domain (in-process) to be aware of. The notified parts usually react somehow to the events.
.NET microservices - Architecture e-book
The concept of time events is prevalent in many real-world scenarios. In a TELCO application, for example, billing cycles are a common occurrence. An event such as CloseBillingCycleEvent
can be triggered by the billing cycle and subsequently processed by other applications. Being oriented around events that hold domain-specific significance is generally easier to understand and maintain than using cron expressions.
This pattern is utilized by the industry. For example, in the Spring Modulith, it is used to trigger events after a specific time event.
Conclusion
When creating domain event-driven applications, the Passage of Time Event pattern is particularly useful where processes or actions need to be triggered based on the passage of time rather than a direct user action or external input.
However, like everything, this pattern is not a silver bullet, it does not fit well in real-time applications, which trigger every second or minute, and also in applications that have dynamic cron expressions.