Skip to content

cihangll/WorkerServiceDemo

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

22 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

en tr

WorkerServiceDemo - English

It is a windows service project that runs at specified times.

Used

It includes 3 sample worker services.

  • "Hello World!" service.
  • Service running every second.
  • Service running the stored procedure as an example.

Running the Project

Follow the steps given below to run the project.

  • appsettings.json change the ConnectionStrings part in the file.
"ConnectionStrings": {
  "Default": "Server=SERVER;Database=DATABASE;User Id=USERNAME;Password=PASSWORD;MultipleActiveResultSets=true"
},
  • Edit the cron and the sp name field. For detailed information about cron click here.
...
"JobSettings": {
    "StoredProcedureName": "uspExample",
    "Cron": "* * * * *"
},

Creating and Using Worker Service

For example, let's assume we want to create a new worker service named DemoWorkerService.

The service needs to be extend from the CronJobService<T> class. We need to send IScheduleConfig and ILogger objects to CronJobService class with dependency injection.

public class DemoWorkerService : CronJobService<DemoWorkerService>
{
	private readonly ILogger<DemoWorkerService> _logger;

	public DemoWorkerService(
		IScheduleConfig<DemoWorkerService> config,
		ILogger<DemoWorkerService> logger
	) : base(config, logger)
	{
		_logger = logger;
	}

	public override Task DoWorkAsync(CancellationToken cancellationToken)
	{
		throw new NotImplementedException();
	}
}

Fill the DoWorkAsync method according to your need.

public override async Task DoWorkAsync(CancellationToken cancellationToken)
{
  //API call or something
  await Task.Delay(3000, cancellationToken);

  // Do stuff...
}

The final version will look like this.

namespace WorkerServiceDemo.Workers;

public class DemoWorkerService : CronJobService<DemoWorkerService>
{
	private readonly ILogger<DemoWorkerService> _logger;

	public DemoWorkerService(
		IScheduleConfig<DemoWorkerService> config,
		ILogger<DemoWorkerService> logger
	) : base(config, logger)
	{
		_logger = logger;
	}

	public override async Task DoWorkAsync(CancellationToken cancellationToken)
	{
		//API call or something
		await Task.Delay(5000, cancellationToken);

		// Do stuff...
	}
}

In order for the DemoWorkerService to work as a service, we need to register in Program.cs. We can use the extension named AddCronJob<T> for this.

var host = Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
//...

  services.AddCronJob<DemoWorkerService>(options =>
  {
    options.CronExpression = "0 * * * *"; //run every hour
    options.TimeZoneInfo = TimeZoneInfo.Local;
  });

})
...

It's that easy. Now, what you write in the DoWorkAsync method will run smoothly at the time intervals you have determined according to the cron expression you have specified.

Installing as a Windows Service

As an example, let's install the windows service installation in the WorkerServiceDemo folder under the C:\\ directory.

  • Open the appsettings.json file. Specify C:\\WorkerServiceDemo directory for logging.
...
  "path": "C:\\WorkerServiceDemo\\Logs\\worker-service-logfile.txt",
...
  • You can set Publish config as follows.

image

  • After compiling the project, click Publish button and extract it to the relevant folder. (Ex: C:\Users\demo\Desktop\WorkerServiceDemo\WorkerServiceNet6\bin\Release\net6.0\win-x64\publish)

image

  • Move the files in the publish folder to the folder where you will install.(Ex; C:\WorkerServiceDemo)

image

  • Run Powershell as administrator and execute command below for install a windows service.
sc.exe create WorkerServiceDemo binpath=C:\WorkerServiceDemo\WorkerServiceDemo.exe start=auto

image

  • To start the service;
sc.exe start WorkerServiceDemo

image

image

  • To stop the service;
sc.exe stop WorkerServiceDemo
  • To delete the service;
sc.exe stop WorkerServiceDemo
sc.exe delete WorkerServiceDemo

image

For more information, you can visit windows-service page.

About

.net core worker service demo with serilog, dapper

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages