CRON basic schedule

The idea behind cron is to schedule tasks at specific interval or period of time.

Library does not provide generic scheduler that would do that automatically for you, instead user should manually implement custom scheduler to periodically check and schedule should cron execute or not.

Tip

A check should be performed at least at minimum cron granularity, that being 1 second in the current revision.

Basic example is very simple and does the following:

  • Parses cron defined by user with :cpp:`lwdtc_cron_parse` function

  • Reads system time periodically (example was tested under Windows environment)

  • It checks if cron is valid for execution each time new time changes versus previous check

  • It executes task

Basic CRON example with parser
 1#include "windows.h"
 2#include <time.h>
 3#include <stdio.h>
 4#include "lwdtc/lwdtc.h"
 5
 6int
 7cron_basic(void) {
 8    /* Define context for CRON, used to parse data to */
 9    lwdtc_cron_ctx_t cron_ctx = {0};
10    struct tm* timeinfo;
11    time_t rawtime, rawtime_old = 0;
12
13    /* Execute cron to be valid every 2 seconds */
14    if (lwdtc_cron_parse(&cron_ctx, "*/2 * * * * * *") != lwdtcOK) {
15        printf("Error parsing CRON...\r\n");
16        while (1) {}
17    }
18    while (1) {
19        /* Get current time and react on changes only */
20        time(&rawtime);
21
22        /* Check if new time has changed versus last read */
23        if (rawtime != rawtime_old) {
24            rawtime_old = rawtime;
25            timeinfo = localtime(&rawtime);
26
27            /* Print time to user */
28            printf("Time: %02d.%02d.%04d %02d:%02d:%02d\r\n",
29                (int)timeinfo->tm_mday, (int)timeinfo->tm_mon, (int)timeinfo->tm_year + 1900,
30                (int)timeinfo->tm_hour, (int)timeinfo->tm_min, (int)timeinfo->tm_sec
31            );
32
33            /* Check if CRON should execute */
34            if (lwdtc_cron_is_valid_for_time(timeinfo, &cron_ctx) == lwdtcOK) {
35                printf("Executing CRON task\r\n");
36            }
37        }
38
39        /* This is sleep from windows.h lib */
40        Sleep(100);
41    }
42    return 0;
43}