CRON multi schedule

Consider a task that has to execute at different times or periods of time, for example:

  • Each Friday at exactly midnight 0 0 0 * * 5 * and

  • Each second every Tuesday * * * * * 2 *

With CRON syntax, it is not possible to describe this with one string, as it does not allow multi range option. Solution is to rather use multiple definitions and then let scheduler to check all of them until at least one is a match.

Tip

LwDTC comes with *_multi functions allowing you to check several CRON contextes with single function call.

An example shows simple demo how to implement a task scheduler which executes at different CRON context-es. It implements calls to _multi functions for simplification

CRON execution at multiple ranges
 1#include "windows.h"
 2#include <time.h>
 3#include <stdio.h>
 4#include "lwdtc/lwdtc.h"
 5
 6/* Define all cron strings to execute one task */
 7static const char* cron_strings[] = {
 8    "* * * * * 2 *",            /* Task should run every second every Tuesday */
 9    "0 0 0 * * 5 *",            /* Task should run every Friday at midnight */
10};
11
12/* Set array of context objects */
13static lwdtc_cron_ctx_t cron_ctxs[LWDTC_ARRAYSIZE(cron_strings)];
14
15int
16cron_multi(void) {
17    /* Define context for CRON, used to parse data to */
18    struct tm* timeinfo;
19    time_t rawtime, rawtime_old = 0;
20    size_t fail_index;
21
22    /* Parse all cron strings */
23    if (lwdtc_cron_parse_multi(cron_ctxs, cron_strings, LWDTC_ARRAYSIZE(cron_ctxs), &fail_index) != lwdtcOK) {
24        printf("Failed to parse cron at index %d\r\n", (int)fail_index);
25        return 0;
26    }
27    printf("CRONs parsed and ready to go\r\n");
28
29    while (1) {
30        /* Get current time and react on changes only */
31        time(&rawtime);
32
33        /* Check if new time has changed versus last read */
34        if (rawtime != rawtime_old) {
35            rawtime_old = rawtime;
36            timeinfo = localtime(&rawtime);
37
38            /* 
39             * Check if CRON should execute for all possible cron objects
40             * 
41             * At least one task should be a pass to execute the task
42             */
43            if (lwdtc_cron_is_valid_for_time_multi_or(timeinfo, cron_ctxs, LWDTC_ARRAYSIZE(cron_ctxs)) == lwdtcOK) {
44                printf("Executing CRON task\r\n");
45            }
46        }
47
48        /* This is sleep from windows.h lib */
49        Sleep(100);
50    }
51    return 0;
52}