Task Scheduler by c# ( Use Hangfire + mongodb)
Task Scheduler is easy for linux server. It modified by admin role so Developer can’t manage task scheduler by themself. Hangfire is the best solution for resolve this problem. It’s support dotnet core ,easy to dev, have dashboard and hight performance.
Ok, step to develop
- New project c# dotnet core Web application
2. add nuget 3 package
- Hangfire.AspNetCore
- Hangfire.Mongo ( for storage data to MongDB )
- MongoDB.Driver ( for storage data to MongDB )
3. add code to connect Mongodb at startup file
Example mongoConnector mongodb://admin:secure@localhost:27017/admin
4. backgroundJobMethod for schedule have 2 choice
4.1 backgroundJob : run at start project .
backgroundJob.Enqueue(() => Console.WriteLine(“Hello world from Hangfire!”));
4.2 RecurringMethod : run recuring from paramether
RecurringJob.AddOrUpdate("some-id", () => task, recurringparmaeter);
recurring important method consist of
- Cron.Daily : run every day
- Cron.Daily(int hour, int minute) : run hour and minute from parameter
- Cron.hour : run every hour
- Cron.Hourly(int minute);
- Cron.MinuteInterval(int interval);
- Cron.MonthInterval(int interval);
- Cron.Weekly(DayOfWeek dayOfWeek, int hour, int minute);
- Cron.Yearly();
- Cron.Yearly(int month);
- Cron.Yearly(int month, int day);
- Cron.Yearly(int month, int day, int hour);
- Cron.Yearly(int month, int day, int hour, int minute);
5. add code for use dashboard
app.UseHangfireDashboard();
* if use hangfire at kubernetes you must craete class authorization ( I custom for every user can read hangfire dashboard )
at startup.cs use code below instand app.UseHangfireDashboard();
app.UseHangfireDashboard(“/hangfire”, new DashboardOptions{ Authorization = new[] { new MyAuthorizationFilter() } });
Then you can run and go to url http://host/hangfire
Mongo data had create automatic
Ok you have schedule api by hangfire and store data from mongo
Reference : hangfire.io