Files
fpc-cron/examples/cron_task.pas

82 lines
2.2 KiB
ObjectPascal

{ cron_task -- minimal example: schedule a daily 3 AM cron task
and verify the cron expression matches the expected times.
Build:
bash build.sh
/opt/fpcup/fpc/bin/x86_64-linux/fpc -O2 -Sh \
-Fusrc -Fu../fpc-db/src -Fu../fpc-events/src \
-FUbuild -FEbuild -obuild/cron_task examples/cron_task.pas
Run:
./build/cron_task }
program cron_task;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}cthreads,{$ENDIF}
Classes, SysUtils, DateUtils,
database.types, database.pool,
log.types, cron.types, cron.runner;
type
THost = class
public
procedure RunTask(const APluginName, ATaskName: string);
procedure Log(Level: TLogLevel; const Category, Msg: string);
end;
procedure THost.RunTask(const APluginName, ATaskName: string);
begin
Writeln('--> ', APluginName, '/', ATaskName);
end;
procedure THost.Log(Level: TLogLevel; const Category, Msg: string);
begin
Writeln('[', LogLevelChar(Level), '] ', Category, ': ', Msg);
end;
var
Pool: TDBPool;
Sched: TCron;
Host: THost;
T1, T2: TDateTime;
DBFile: string;
begin
Writeln('cron expression sanity check (no DB, no thread):');
T1 := EncodeDate(2026, 5, 5) + EncodeTime(3, 0, 0, 0);
T2 := EncodeDate(2026, 5, 5) + EncodeTime(3, 1, 0, 0);
Writeln(' "0 3 * * *" matches 03:00 = ',
TCron.MatchesCron('0 3 * * *', T1));
Writeln(' "0 3 * * *" matches 03:01 = ',
TCron.MatchesCron('0 3 * * *', T2));
Writeln;
Writeln('persisting a cron task in system_scheduler:');
DBFile := '/tmp/fpcsched_cron_' + IntToStr(GetProcessID) + '.sqlite3';
if FileExists(DBFile) then DeleteFile(DBFile);
Pool := TDBPool.Create;
Pool.Init(dbSQLite, DBFile);
Host := THost.Create;
try
Sched := TCron.Create(Pool, @Host.RunTask, nil, @Host.Log);
try
Pool.ExecSQL(
'INSERT INTO system_scheduler ' +
'(task_name, plugin_name, schedule_type, cron_expr, enabled, ' +
' description) VALUES ' +
'(''nightly'', ''demo'', ''cron'', ''0 3 * * *'', 1, ''nightly run'')');
Sched.RefreshTasks;
Writeln(' scheduled -- next_run computed and stored in DB');
finally
Sched.Free;
end;
finally
Host.Free;
Pool.Free;
DeleteFile(DBFile);
end;
end.