Task Scheduling
- Introduction
- Complete Example: Schedule a Real Command
- Defining Schedules
- Running the Scheduler
- Task Hooks
Complete Example: Schedule a Real Command
First add the complete GreetDemo command. Inside the template's existing ConsoleRoutes.Map() in routes/console.cs, add:
Schedule.Command("demo:greet Ada --times=1")
.EveryMinute()
.Timezone("UTC");The generated RouteServiceProvider.Boot already calls ConsoleRoutes.Map(). From the application directory:
dotblaze demo:greet Ada --times=1
dotblaze schedule:list
dotblaze schedule:runExpected: the direct call greets Ada; the schedule list contains * * * * *; schedule:run invokes the due task. It is a one-shot runner. Use dotblaze schedule:work for local continuous execution, or the cron/systemd setup below for deployment.
If the real command must not overlap, configure a shared cache first, then append .WithoutOverlapping(5). A cron-created process cannot reuse another process's memory lock. Use a suitable lock expiry for the command's maximum duration. Explicit .Timezone("UTC") also makes list/test output independent of the application's default timezone.
Introduction
Instead of one cron entry per task, DotBlaze's scheduler lets you define every recurring task in code, like Laravel's. The server needs a single cron entry that runs schedule:run every minute (or a schedule:work process); the scheduler decides which tasks are due.
Tasks are defined in routes/console.cs, which RouteServiceProvider calls while the application boots:
namespace App.Routes;
public static class ConsoleRoutes
{
public static void Map()
{
Schedule.Command("queue:prune-batches --hours=48").Daily();
Schedule.Call(() => Cache.Forget("post-stats")).Hourly().Name("refresh-post-stats");
}
}dotblaze schedule:list shows every task with its cron expression and the next time it runs.
Defining Schedules
Scheduling Commands
Schedule.Command runs a console command in-process, with its arguments and options:
Schedule.Command("emails:send Taylor --force").Daily();A command that returns a non-zero exit code counts as a failure.
Scheduling Queued Jobs
Schedule.Job dispatches a job; a queued job is pushed and runs on the worker:
Schedule.Job(new Heartbeat()).EveryFiveMinutes();
Schedule.Job(new Heartbeat(), queue: "heartbeats", connection: "redis").EveryFiveMinutes();Scheduling Closures
Schedule.Call(async () =>
{
await DB.Table("recent_users").Delete();
}).Daily().Name("clear-recent-users");Facades and models work inside: each run has its own service scope, like a request.
Schedule Frequency Options
| Method | Runs |
|---|---|
Cron("* * * * *") | On a custom cron expression. |
EveryMinute(), EveryTwoMinutes(), EveryThreeMinutes(), EveryFourMinutes(), EveryFiveMinutes(), EveryTenMinutes(), EveryFifteenMinutes(), EveryThirtyMinutes() | Every n minutes. |
Hourly(), HourlyAt(17) | Every hour (at minute 17). |
EveryTwoHours(), EveryThreeHours(), EveryFourHours(), EverySixHours() | Every n hours (optionally at a minute). |
Daily(), DailyAt("13:00"), TwiceDaily(1, 13) | Every day at midnight, at 13:00, at 1:00 and 13:00. |
Weekly(), WeeklyOn(DayOfWeek.Monday, "8:00") | Every Sunday at midnight, every Monday at 8:00. |
Monthly(), MonthlyOn(4, "15:00"), LastDayOfMonth("15:00") | On the first, the fourth, the last day of the month. |
Quarterly(), Yearly() | On the first day of every quarter, of every year. |
Combine them with day constraints and At:
Schedule.Command("reports:send").Weekdays().At("8:00");
Schedule.Command("backups:run").Days(DayOfWeek.Monday, DayOfWeek.Thursday).At("2:30");Weekdays(), Weekends(), Mondays() ... Sundays(), and Days(...) limit the days of the week. Cron expressions support *, lists, ranges, steps (*/10), and L for the last day of the month.
Timezones
Schedules are evaluated in UTC, or in app.timezone from config/App.cs when it is set. One task can use another zone:
Schedule.Command("report:generate").Timezone("Asia/Jakarta").DailyAt("7:00");Conditions
Schedule.Command("emails:send").Daily().When(() => Config.Get<bool>("mail.digest"));
Schedule.Command("emails:send").Daily().Skip(() => DateTime.UtcNow.Day == 1);
Schedule.Command("emails:send").Hourly().Between("7:00", "22:00");
Schedule.Command("emails:send").Hourly().UnlessBetween("23:00", "4:00");
Schedule.Command("emails:send").Daily().Environments("Production");When and Skip also accept async conditions. Between windows may cross midnight.
Preventing Task Overlaps
WithoutOverlapping() skips a run while the previous one is still going. It is a cache lock that expires after 24 hours (or WithoutOverlapping(minutes)) in case a run never finishes:
Schedule.Command("emails:send").EveryMinute().WithoutOverlapping();Separate schedule:run processes do not share the memory cache, even on one machine. Select a shared database or Redis cache store before relying on this lock. Use the same store, task name, and expiration on every scheduler process.
Running Tasks on One Server
When several servers run schedule:run, OnOneServer() lets only the first one run the task for each due time. Use a shared cache store (redis) for it:
Schedule.Command("report:generate").Daily().OnOneServer();A closure needs a Name(...) to use WithoutOverlapping or OnOneServer; it identifies the lock.
Background Tasks
Tasks due at the same time run one after another. RunInBackground() starts a long task without making the next one wait; schedule:run still waits for it before exiting:
Schedule.Command("analytics:report").Daily().RunInBackground();Running the Scheduler
Add one cron entry on the server that runs schedule:run every minute, from the app's directory:
* * * * * cd /var/www/app && dotnet App.dll schedule:run >> /dev/null 2>&1Where cron is not available (containers), run schedule:work as a long-running process instead, under the same supervisor as your queue workers. It wakes up at the start of every minute and runs the due tasks.
A failing task is logged and does not stop the other tasks.
Running the Scheduler Locally
dotblaze schedule:workdotblaze schedule:test <number or name> runs one task right away, whether or not it is due.
Task Hooks
Schedule.Command("emails:send").Daily()
.Before(async () => { /* the task is about to run */ })
.After(async () => { /* the task ran, whatever the outcome */ })
.OnSuccess(async () => { ... })
.OnFailure(async exception => await Notification.Route("mail", "ops@example.com").Notify(new TaskFailed { Error = exception.Message }));