├── .github
└── FUNDING.yml
├── .gitignore
├── LICENSE
├── README.md
├── ServiceWorkerCronJobDemo.sln
├── ServiceWorkerCronJobDemo
├── Controllers
│ └── WeatherForecastController.cs
├── Program.cs
├── ServiceWorkerCronJobDemo.csproj
├── Services
│ ├── CronJobService.cs
│ ├── MyCronJob1.cs
│ ├── MyCronJob2.cs
│ ├── MyCronJob3.cs
│ └── MyScopedService.cs
├── Startup.cs
├── appsettings.Development.json
└── appsettings.json
└── cron-jobs.gif
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
4 | patreon: # Replace with a single Patreon username
5 | open_collective: # Replace with a single Open Collective username
6 | ko_fi: changhuixu
7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9 | liberapay: # Replace with a single Liberapay username
10 | issuehunt: # Replace with a single IssueHunt username
11 | otechie: # Replace with a single Otechie username
12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
13 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.suo
8 | *.user
9 | *.userosscache
10 | *.sln.docstates
11 |
12 | # User-specific files (MonoDevelop/Xamarin Studio)
13 | *.userprefs
14 |
15 | # Build results
16 | [Dd]ebug/
17 | [Dd]ebugPublic/
18 | [Rr]elease/
19 | [Rr]eleases/
20 | x64/
21 | x86/
22 | bld/
23 | [Bb]in/
24 | [Oo]bj/
25 | [Ll]og/
26 |
27 | # Visual Studio 2015/2017 cache/options directory
28 | .vs/
29 | # Uncomment if you have tasks that create the project's static files in wwwroot
30 | #wwwroot/
31 |
32 | # Visual Studio 2017 auto generated files
33 | Generated\ Files/
34 |
35 | # MSTest test Results
36 | [Tt]est[Rr]esult*/
37 | [Bb]uild[Ll]og.*
38 |
39 | # NUNIT
40 | *.VisualState.xml
41 | TestResult.xml
42 |
43 | # Build Results of an ATL Project
44 | [Dd]ebugPS/
45 | [Rr]eleasePS/
46 | dlldata.c
47 |
48 | # Benchmark Results
49 | BenchmarkDotNet.Artifacts/
50 |
51 | # .NET Core
52 | project.lock.json
53 | project.fragment.lock.json
54 | artifacts/
55 | **/Properties/launchSettings.json
56 |
57 | # StyleCop
58 | StyleCopReport.xml
59 |
60 | # Files built by Visual Studio
61 | *_i.c
62 | *_p.c
63 | *_i.h
64 | *.ilk
65 | *.meta
66 | *.obj
67 | *.iobj
68 | *.pch
69 | *.pdb
70 | *.ipdb
71 | *.pgc
72 | *.pgd
73 | *.rsp
74 | *.sbr
75 | *.tlb
76 | *.tli
77 | *.tlh
78 | *.tmp
79 | *.tmp_proj
80 | *.log
81 | *.vspscc
82 | *.vssscc
83 | .builds
84 | *.pidb
85 | *.svclog
86 | *.scc
87 |
88 | # Chutzpah Test files
89 | _Chutzpah*
90 |
91 | # Visual C++ cache files
92 | ipch/
93 | *.aps
94 | *.ncb
95 | *.opendb
96 | *.opensdf
97 | *.sdf
98 | *.cachefile
99 | *.VC.db
100 | *.VC.VC.opendb
101 |
102 | # Visual Studio profiler
103 | *.psess
104 | *.vsp
105 | *.vspx
106 | *.sap
107 |
108 | # Visual Studio Trace Files
109 | *.e2e
110 |
111 | # TFS 2012 Local Workspace
112 | $tf/
113 |
114 | # Guidance Automation Toolkit
115 | *.gpState
116 |
117 | # ReSharper is a .NET coding add-in
118 | _ReSharper*/
119 | *.[Rr]e[Ss]harper
120 | *.DotSettings.user
121 |
122 | # JustCode is a .NET coding add-in
123 | .JustCode
124 |
125 | # TeamCity is a build add-in
126 | _TeamCity*
127 |
128 | # DotCover is a Code Coverage Tool
129 | *.dotCover
130 |
131 | # AxoCover is a Code Coverage Tool
132 | .axoCover/*
133 | !.axoCover/settings.json
134 |
135 | # Visual Studio code coverage results
136 | *.coverage
137 | *.coveragexml
138 |
139 | # NCrunch
140 | _NCrunch_*
141 | .*crunch*.local.xml
142 | nCrunchTemp_*
143 |
144 | # MightyMoose
145 | *.mm.*
146 | AutoTest.Net/
147 |
148 | # Web workbench (sass)
149 | .sass-cache/
150 |
151 | # Installshield output folder
152 | [Ee]xpress/
153 |
154 | # DocProject is a documentation generator add-in
155 | DocProject/buildhelp/
156 | DocProject/Help/*.HxT
157 | DocProject/Help/*.HxC
158 | DocProject/Help/*.hhc
159 | DocProject/Help/*.hhk
160 | DocProject/Help/*.hhp
161 | DocProject/Help/Html2
162 | DocProject/Help/html
163 |
164 | # Click-Once directory
165 | publish/
166 |
167 | # Publish Web Output
168 | *.[Pp]ublish.xml
169 | *.azurePubxml
170 | # Note: Comment the next line if you want to checkin your web deploy settings,
171 | # but database connection strings (with potential passwords) will be unencrypted
172 | *.pubxml
173 | *.publishproj
174 |
175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
176 | # checkin your Azure Web App publish settings, but sensitive information contained
177 | # in these scripts will be unencrypted
178 | PublishScripts/
179 |
180 | # NuGet Packages
181 | *.nupkg
182 | # The packages folder can be ignored because of Package Restore
183 | **/[Pp]ackages/*
184 | # except build/, which is used as an MSBuild target.
185 | !**/[Pp]ackages/build/
186 | # Uncomment if necessary however generally it will be regenerated when needed
187 | #!**/[Pp]ackages/repositories.config
188 | # NuGet v3's project.json files produces more ignorable files
189 | *.nuget.props
190 | *.nuget.targets
191 |
192 | # Microsoft Azure Build Output
193 | csx/
194 | *.build.csdef
195 |
196 | # Microsoft Azure Emulator
197 | ecf/
198 | rcf/
199 |
200 | # Windows Store app package directories and files
201 | AppPackages/
202 | BundleArtifacts/
203 | Package.StoreAssociation.xml
204 | _pkginfo.txt
205 | *.appx
206 |
207 | # Visual Studio cache files
208 | # files ending in .cache can be ignored
209 | *.[Cc]ache
210 | # but keep track of directories ending in .cache
211 | !*.[Cc]ache/
212 |
213 | # Others
214 | ClientBin/
215 | ~$*
216 | *~
217 | *.dbmdl
218 | *.dbproj.schemaview
219 | *.jfm
220 | *.pfx
221 | *.publishsettings
222 | orleans.codegen.cs
223 |
224 | # Including strong name files can present a security risk
225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
226 | #*.snk
227 |
228 | # Since there are multiple workflows, uncomment next line to ignore bower_components
229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
230 | #bower_components/
231 |
232 | # RIA/Silverlight projects
233 | Generated_Code/
234 |
235 | # Backup & report files from converting an old project file
236 | # to a newer Visual Studio version. Backup files are not needed,
237 | # because we have git ;-)
238 | _UpgradeReport_Files/
239 | Backup*/
240 | UpgradeLog*.XML
241 | UpgradeLog*.htm
242 | ServiceFabricBackup/
243 | *.rptproj.bak
244 |
245 | # SQL Server files
246 | *.mdf
247 | *.ldf
248 | *.ndf
249 |
250 | # Business Intelligence projects
251 | *.rdl.data
252 | *.bim.layout
253 | *.bim_*.settings
254 | *.rptproj.rsuser
255 |
256 | # Microsoft Fakes
257 | FakesAssemblies/
258 |
259 | # GhostDoc plugin setting file
260 | *.GhostDoc.xml
261 |
262 | # Node.js Tools for Visual Studio
263 | .ntvs_analysis.dat
264 | node_modules/
265 |
266 | # Visual Studio 6 build log
267 | *.plg
268 |
269 | # Visual Studio 6 workspace options file
270 | *.opt
271 |
272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
273 | *.vbw
274 |
275 | # Visual Studio LightSwitch build output
276 | **/*.HTMLClient/GeneratedArtifacts
277 | **/*.DesktopClient/GeneratedArtifacts
278 | **/*.DesktopClient/ModelManifest.xml
279 | **/*.Server/GeneratedArtifacts
280 | **/*.Server/ModelManifest.xml
281 | _Pvt_Extensions
282 |
283 | # Paket dependency manager
284 | .paket/paket.exe
285 | paket-files/
286 |
287 | # FAKE - F# Make
288 | .fake/
289 |
290 | # JetBrains Rider
291 | .idea/
292 | *.sln.iml
293 |
294 | # CodeRush
295 | .cr/
296 |
297 | # Python Tools for Visual Studio (PTVS)
298 | __pycache__/
299 | *.pyc
300 |
301 | # Cake - Uncomment if you are using it
302 | # tools/**
303 | # !tools/packages.config
304 |
305 | # Tabs Studio
306 | *.tss
307 |
308 | # Telerik's JustMock configuration file
309 | *.jmconfig
310 |
311 | # BizTalk build output
312 | *.btp.cs
313 | *.btm.cs
314 | *.odx.cs
315 | *.xsd.cs
316 |
317 | # OpenCover UI analysis results
318 | OpenCover/
319 |
320 | # Azure Stream Analytics local run output
321 | ASALocalRun/
322 |
323 | # MSBuild Binary and Structured Log
324 | *.binlog
325 |
326 | # NVidia Nsight GPU debugger configuration file
327 | *.nvuser
328 |
329 | # MFractors (Xamarin productivity tool) working folder
330 | .mfractor/
331 |
332 | CSharpLabs/RunExeFromWebApi/WebApi/App_Data/
333 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 Changhui Xu
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Service Worker Cron Jobs Demo
2 |
3 |
4 |
5 | You may want to ask, "_What's the difference between a hosted service and a background thread?_" The difference is that the hosted service will be started and stopped with the application. While, when starting a background thread, the thread cannot gracefully handle clean-up actions and will be killed when the application is stopped. The `HostedServiceExecutor` will handle the starting and stopping of a hosted service, which allows for graceful cleanup when the application is stopped.
6 |
7 | Starts from version 2.1, .NET Core provides a native abstract base class `BackgroundService`, which includes common operations for background jobs such as `CancellationToken` and housekeeping works.
8 |
9 | ## [Medium Article: Schedule Cron Jobs using HostedService in ASP.NET Core](https://codeburst.io/schedule-cron-jobs-using-hostedservice-in-asp-net-core-e17c47ba06)
10 |
11 | In this blog post, we will go over the use case of scheduling cron jobs using a customized `HostedService` in an ASP.NET Core Web API project. The following screen recording shows the runtime logging for the final application, which has three background tasks running at every 5 minutes, every 1 minute, and every day at 12:50 PM.
12 |
13 | 
14 |
15 | ## License
16 |
17 | Feel free to use the code in this repository as it is under MIT license.
18 |
19 |
20 |
--------------------------------------------------------------------------------
/ServiceWorkerCronJobDemo.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.3.32901.215
5 | MinimumVisualStudioVersion = 15.0.26124.0
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ServiceWorkerCronJobDemo", "ServiceWorkerCronJobDemo\ServiceWorkerCronJobDemo.csproj", "{B82EDA18-CDF0-4C13-B808-4D9DA73A88A7}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Debug|x64 = Debug|x64
12 | Debug|x86 = Debug|x86
13 | Release|Any CPU = Release|Any CPU
14 | Release|x64 = Release|x64
15 | Release|x86 = Release|x86
16 | EndGlobalSection
17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
18 | {B82EDA18-CDF0-4C13-B808-4D9DA73A88A7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
19 | {B82EDA18-CDF0-4C13-B808-4D9DA73A88A7}.Debug|Any CPU.Build.0 = Debug|Any CPU
20 | {B82EDA18-CDF0-4C13-B808-4D9DA73A88A7}.Debug|x64.ActiveCfg = Debug|Any CPU
21 | {B82EDA18-CDF0-4C13-B808-4D9DA73A88A7}.Debug|x64.Build.0 = Debug|Any CPU
22 | {B82EDA18-CDF0-4C13-B808-4D9DA73A88A7}.Debug|x86.ActiveCfg = Debug|Any CPU
23 | {B82EDA18-CDF0-4C13-B808-4D9DA73A88A7}.Debug|x86.Build.0 = Debug|Any CPU
24 | {B82EDA18-CDF0-4C13-B808-4D9DA73A88A7}.Release|Any CPU.ActiveCfg = Release|Any CPU
25 | {B82EDA18-CDF0-4C13-B808-4D9DA73A88A7}.Release|Any CPU.Build.0 = Release|Any CPU
26 | {B82EDA18-CDF0-4C13-B808-4D9DA73A88A7}.Release|x64.ActiveCfg = Release|Any CPU
27 | {B82EDA18-CDF0-4C13-B808-4D9DA73A88A7}.Release|x64.Build.0 = Release|Any CPU
28 | {B82EDA18-CDF0-4C13-B808-4D9DA73A88A7}.Release|x86.ActiveCfg = Release|Any CPU
29 | {B82EDA18-CDF0-4C13-B808-4D9DA73A88A7}.Release|x86.Build.0 = Release|Any CPU
30 | EndGlobalSection
31 | GlobalSection(SolutionProperties) = preSolution
32 | HideSolutionNode = FALSE
33 | EndGlobalSection
34 | GlobalSection(ExtensibilityGlobals) = postSolution
35 | SolutionGuid = {6C804728-BEF0-4F26-88E0-08C15C379B7A}
36 | EndGlobalSection
37 | EndGlobal
38 |
--------------------------------------------------------------------------------
/ServiceWorkerCronJobDemo/Controllers/WeatherForecastController.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Mvc;
2 |
3 | namespace ServiceWorkerCronJobDemo.Controllers;
4 |
5 | [ApiController]
6 | [Route("[controller]")]
7 | public class WeatherForecastController : ControllerBase
8 | {
9 | private static readonly string[] Summaries = { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" };
10 |
11 | [HttpGet]
12 | public IEnumerable Get()
13 | {
14 | var rng = new Random();
15 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast
16 | {
17 | Date = DateTime.Now.AddDays(index),
18 | TemperatureC = rng.Next(-20, 55),
19 | Summary = Summaries[rng.Next(Summaries.Length)]
20 | })
21 | .ToArray();
22 | }
23 | }
24 |
25 | public class WeatherForecast
26 | {
27 | public DateTime Date { get; set; }
28 |
29 | public int TemperatureC { get; set; }
30 |
31 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
32 |
33 | public string Summary { get; set; } = string.Empty;
34 | }
--------------------------------------------------------------------------------
/ServiceWorkerCronJobDemo/Program.cs:
--------------------------------------------------------------------------------
1 | namespace ServiceWorkerCronJobDemo;
2 |
3 | public class Program
4 | {
5 | public static void Main(string[] args)
6 | {
7 | CreateHostBuilder(args).Build().Run();
8 | }
9 |
10 | public static IHostBuilder CreateHostBuilder(string[] args) =>
11 | Host.CreateDefaultBuilder(args)
12 | .ConfigureWebHostDefaults(webBuilder =>
13 | {
14 | webBuilder.UseStartup();
15 | });
16 | }
--------------------------------------------------------------------------------
/ServiceWorkerCronJobDemo/ServiceWorkerCronJobDemo.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net8.0
5 | enable
6 | enable
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/ServiceWorkerCronJobDemo/Services/CronJobService.cs:
--------------------------------------------------------------------------------
1 | using Cronos;
2 |
3 | namespace ServiceWorkerCronJobDemo.Services;
4 |
5 | public abstract class CronJobService(string cronExpression, TimeZoneInfo timeZoneInfo, ILogger logger) : IHostedService, IDisposable
6 | {
7 | private System.Timers.Timer? _timer;
8 | private readonly CronExpression _expression = CronExpression.Parse(cronExpression);
9 | private Task? _executingTask;
10 | private CancellationTokenSource _stoppingCts = new();
11 | private readonly SemaphoreSlim _schedulerCycle = new(0);
12 |
13 | public virtual Task StartAsync(CancellationToken cancellationToken)
14 | {
15 | logger.LogInformation("{jobName}: started with expression [{expression}].", GetType().Name, cronExpression);
16 | _stoppingCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
17 |
18 | _executingTask = ScheduleJob(_stoppingCts.Token);
19 | return _executingTask.IsCompleted ? _executingTask : Task.CompletedTask;
20 | }
21 |
22 | protected virtual async Task ScheduleJob(CancellationToken cancellationToken)
23 | {
24 | try
25 | {
26 | while (!cancellationToken.IsCancellationRequested)
27 | {
28 | var next = _expression.GetNextOccurrence(DateTimeOffset.Now, timeZoneInfo);
29 | if (!next.HasValue) continue;
30 |
31 | logger.LogInformation("{jobName}: scheduled next run at {nextRun}", GetType().Name, next.ToString());
32 | var delay = next.Value - DateTimeOffset.Now;
33 | if (delay.TotalMilliseconds <= 0) // prevent non-positive values from being passed into Timer
34 | {
35 | logger.LogInformation("{LoggerName}: scheduled next run is in the past. Moving to next.", GetType().Name);
36 | continue;
37 | }
38 |
39 | _timer = new System.Timers.Timer(delay.TotalMilliseconds);
40 | _timer.Elapsed += async (_, _) =>
41 | {
42 | try
43 | {
44 | _timer.Dispose(); // reset and dispose timer
45 | _timer = null;
46 |
47 | if (!cancellationToken.IsCancellationRequested)
48 | {
49 | await DoWork(cancellationToken);
50 | }
51 | }
52 | catch (OperationCanceledException)
53 | {
54 | logger.LogInformation("{LoggerName}: job received cancellation signal, stopping...", GetType().Name);
55 | }
56 | catch (Exception e)
57 | {
58 | logger.LogError(e, "{LoggerName}: an error happened during execution of the job", GetType().Name);
59 | }
60 | finally
61 | {
62 | _schedulerCycle.Release(); // Let the outer loop know that the next occurrence can be calculated.
63 | }
64 | };
65 | _timer.Start();
66 | await _schedulerCycle.WaitAsync(cancellationToken); // Wait nicely for any timer result.
67 | }
68 | }
69 | catch (OperationCanceledException)
70 | {
71 | logger.LogInformation("{LoggerName}: job received cancellation signal, stopping...", GetType().Name);
72 | }
73 | }
74 |
75 | public virtual async Task DoWork(CancellationToken cancellationToken)
76 | {
77 | await Task.Delay(5000, cancellationToken); // do the work
78 | }
79 |
80 | public virtual async Task StopAsync(CancellationToken cancellationToken)
81 | {
82 | logger.LogInformation("{jobName}: stopping...", GetType().Name);
83 | _timer?.Stop();
84 | _timer?.Dispose();
85 | await _stoppingCts.CancelAsync();
86 | logger.LogInformation("{jobName}: stopped.", GetType().Name);
87 | }
88 |
89 | public virtual void Dispose()
90 | {
91 | _timer?.Dispose();
92 | _executingTask?.Dispose();
93 | _schedulerCycle.Dispose();
94 | _stoppingCts.Dispose();
95 | GC.SuppressFinalize(this);
96 | }
97 | }
98 |
99 | // ReSharper disable once UnusedTypeParameter
100 | public interface IScheduleConfig
101 | {
102 | string CronExpression { get; set; }
103 | TimeZoneInfo TimeZoneInfo { get; set; }
104 | }
105 |
106 | public class ScheduleConfig : IScheduleConfig
107 | {
108 | public string CronExpression { get; set; } = string.Empty;
109 | public TimeZoneInfo TimeZoneInfo { get; set; } = TimeZoneInfo.Local;
110 | }
111 |
112 | public static class ScheduledServiceExtensions
113 | {
114 | public static IServiceCollection AddCronJob(this IServiceCollection services, Action> options) where T : CronJobService
115 | {
116 | if (options == null)
117 | {
118 | throw new ArgumentNullException(nameof(options), "Please provide Schedule Configurations.");
119 | }
120 | var config = new ScheduleConfig();
121 | options.Invoke(config);
122 | if (string.IsNullOrWhiteSpace(config.CronExpression))
123 | {
124 | throw new ArgumentNullException(nameof(options), "Empty Cron Expression is not allowed.");
125 | }
126 |
127 | services.AddSingleton>(config);
128 | services.AddHostedService();
129 | return services;
130 | }
131 | }
--------------------------------------------------------------------------------
/ServiceWorkerCronJobDemo/Services/MyCronJob1.cs:
--------------------------------------------------------------------------------
1 | namespace ServiceWorkerCronJobDemo.Services;
2 |
3 | public class MyCronJob1(IScheduleConfig config, ILogger logger)
4 | : CronJobService(config.CronExpression, config.TimeZoneInfo, logger)
5 | {
6 | public override Task StartAsync(CancellationToken cancellationToken)
7 | {
8 | logger.LogInformation("CronJob 1 starts.");
9 | return base.StartAsync(cancellationToken);
10 | }
11 |
12 | public override Task DoWork(CancellationToken cancellationToken)
13 | {
14 | logger.LogInformation("{now} CronJob 1 is working.", DateTime.Now.ToString("T"));
15 | return Task.CompletedTask;
16 | }
17 |
18 | public override Task StopAsync(CancellationToken cancellationToken)
19 | {
20 | logger.LogInformation("CronJob 1 is stopping.");
21 | return base.StopAsync(cancellationToken);
22 | }
23 | }
--------------------------------------------------------------------------------
/ServiceWorkerCronJobDemo/Services/MyCronJob2.cs:
--------------------------------------------------------------------------------
1 | namespace ServiceWorkerCronJobDemo.Services;
2 |
3 | public class MyCronJob2 : CronJobService
4 | {
5 | private readonly ILogger _logger;
6 | private readonly IServiceProvider _serviceProvider;
7 |
8 | public MyCronJob2(IScheduleConfig config, ILogger logger, IServiceProvider serviceProvider)
9 | : base(config.CronExpression, config.TimeZoneInfo, logger)
10 | {
11 | _logger = logger;
12 | _serviceProvider = serviceProvider;
13 | if (config.GetType().GenericTypeArguments[0].Name != GetType().Name)
14 | {
15 | throw new ArgumentException("Incorrect JobType name for IScheduleConfig.");
16 | }
17 | if (logger.GetType().GenericTypeArguments[0].Name != GetType().Name)
18 | {
19 | throw new ArgumentException("Incorrect JobType name for ILogger.");
20 | }
21 | }
22 |
23 | public override async Task DoWork(CancellationToken cancellationToken)
24 | {
25 | _logger.LogInformation("{now} CronJob 2 is working.", DateTime.Now.ToString("T"));
26 | using var scope = _serviceProvider.CreateScope();
27 | var svc = scope.ServiceProvider.GetRequiredService();
28 | await svc.DoWork(cancellationToken);
29 | }
30 | }
--------------------------------------------------------------------------------
/ServiceWorkerCronJobDemo/Services/MyCronJob3.cs:
--------------------------------------------------------------------------------
1 | namespace ServiceWorkerCronJobDemo.Services;
2 |
3 | public class MyCronJob3 : CronJobService
4 | {
5 | private readonly ILogger _logger;
6 |
7 | public MyCronJob3(IScheduleConfig config, ILogger logger)
8 | : base(config.CronExpression, config.TimeZoneInfo, logger)
9 | {
10 | _logger = logger;
11 | if (config.GetType().GenericTypeArguments[0].Name != GetType().Name)
12 | {
13 | throw new ArgumentException("Incorrect JobType name for IScheduleConfig.");
14 | }
15 | if (logger.GetType().GenericTypeArguments[0].Name != GetType().Name)
16 | {
17 | throw new ArgumentException("Incorrect JobType name for ILogger.");
18 | }
19 | }
20 |
21 | public override Task StartAsync(CancellationToken cancellationToken)
22 | {
23 | _logger.LogInformation("CronJob 3 starts.");
24 | return base.StartAsync(cancellationToken);
25 | }
26 |
27 | public override Task DoWork(CancellationToken cancellationToken)
28 | {
29 | _logger.LogInformation("{now} CronJob 3 is working.", DateTime.Now.ToString("T"));
30 | return Task.CompletedTask;
31 | }
32 |
33 | public override Task StopAsync(CancellationToken cancellationToken)
34 | {
35 | _logger.LogInformation("CronJob 3 is stopping.");
36 | return base.StopAsync(cancellationToken);
37 | }
38 | }
--------------------------------------------------------------------------------
/ServiceWorkerCronJobDemo/Services/MyScopedService.cs:
--------------------------------------------------------------------------------
1 | namespace ServiceWorkerCronJobDemo.Services;
2 |
3 | public interface IMyScopedService
4 | {
5 | Task DoWork(CancellationToken cancellationToken);
6 | }
7 |
8 | public class MyScopedService(ILogger logger) : IMyScopedService
9 | {
10 | public Task DoWork(CancellationToken cancellationToken)
11 | {
12 | logger.LogInformation("{now} MyScopedService is working.", DateTime.Now.ToString("T"));
13 | return Task.Delay(1000 * 20, cancellationToken);
14 | }
15 | }
--------------------------------------------------------------------------------
/ServiceWorkerCronJobDemo/Startup.cs:
--------------------------------------------------------------------------------
1 | using ServiceWorkerCronJobDemo.Services;
2 |
3 | namespace ServiceWorkerCronJobDemo;
4 |
5 | public class Startup
6 | {
7 | public void ConfigureServices(IServiceCollection services)
8 | {
9 | services.AddControllers();
10 |
11 | services.AddScoped();
12 |
13 | services.AddCronJob(c =>
14 | {
15 | c.TimeZoneInfo = TimeZoneInfo.Local;
16 | c.CronExpression = "*/5 * * * *";
17 | });
18 | // MyCronJob2 calls the scoped service MyScopedService
19 | services.AddCronJob(c =>
20 | {
21 | c.TimeZoneInfo = TimeZoneInfo.Local;
22 | c.CronExpression = "* * * * *";
23 | });
24 | services.AddCronJob(c =>
25 | {
26 | c.TimeZoneInfo = TimeZoneInfo.Local;
27 | c.CronExpression = "50 12 * * *";
28 | });
29 | }
30 |
31 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
32 | {
33 | if (env.IsDevelopment())
34 | {
35 | app.UseDeveloperExceptionPage();
36 | }
37 |
38 | app.UseRouting();
39 |
40 | app.UseAuthorization();
41 |
42 | app.UseEndpoints(endpoints =>
43 | {
44 | endpoints.MapControllers();
45 | });
46 | }
47 | }
--------------------------------------------------------------------------------
/ServiceWorkerCronJobDemo/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft": "Warning",
6 | "Microsoft.Hosting.Lifetime": "Warning"
7 | }
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/ServiceWorkerCronJobDemo/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft": "Warning",
6 | "Microsoft.Hosting.Lifetime": "Information"
7 | }
8 | },
9 | "AllowedHosts": "*"
10 | }
11 |
--------------------------------------------------------------------------------
/cron-jobs.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dotnet-labs/ServiceWorkerCronJob/df374bb41a6a751236768519448a633c8ba8a65d/cron-jobs.gif
--------------------------------------------------------------------------------