I notice that when I create my scheduled task for the first time at application startup, it executes immediately even though it was created with a cron expression many hours in the future. Is this normal behavior? Is there a way to prevent that? If i would use the RunAfter with the same datetime of the next cron execution, will it fire twice? Or I could find the next cron execution and then prevent it from running if it is now yet the time?
You would need to set the Scheduled Task’s LastRun in the db, something like:
IBackgroundJobs jobs = feature.Jobs; // or IOC
using var dbJobs = jobs.OpenDb();
dbJobs.UpdateOnly(() => new ScheduledTask {
LastRun = DateTime.UtcNow,
}, where:x => x.Name == taskName);