Task Scheduler by c# ( Use Hangfire + mongodb)

Phumipat Chomwattana
2 min readOct 1, 2020

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

  1. New project c# dotnet core Web application
new project

2. add nuget 3 package

  • Hangfire.AspNetCore
  • Hangfire.Mongo ( for storage data to MongDB )
  • MongoDB.Driver ( for storage data to MongDB )
neget package

3. add code to connect Mongodb at startup file

startup.cs

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

  1. Cron.Daily : run every day
  2. Cron.Daily(int hour, int minute) : run hour and minute from parameter
  3. Cron.hour : run every hour
  4. Cron.Hourly(int minute);
  5. Cron.MinuteInterval(int interval);
  6. Cron.MonthInterval(int interval);
  7. Cron.Weekly(DayOfWeek dayOfWeek, int hour, int minute);
  8. Cron.Yearly();
  9. Cron.Yearly(int month);
  10. Cron.Yearly(int month, int day);
  11. Cron.Yearly(int month, int day, int hour);
  12. 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

hangfire dashboard

Mongo data had create automatic

hangfire data in mongo

Ok you have schedule api by hangfire and store data from mongo

Reference : hangfire.io

--

--