How to call a method at a specific time every day or once?
1 answer
The problem of calling a method on a schedule is not solved in general. The fact is that at the right time your program may not work at all!
Therefore, for a start, you need to think of a way to start the program on this very schedule.
There are three possible options:
Windows Scheduler. Sometimes it seems that they have forgotten about him - but over time it only gets better. And if on the same XP the administrator often turned off the scheduler, then in the latest versions of Windows, it is usually still left enabled, because many useful programs and services are tied to it.
More details about creating a task in the windows scheduler can be found here: Creating Scheduled Tasks
SQL Server Agent. If you use SQL Server (and quite a few projects use it), then its agent will be somewhere nearby. The procedure for creating a task is described on MSDN (it uses stored procedures - that is, you will need a connection to the database and server administrator rights).
In both cases, you will need some way to call not the program as a whole, but a specific method. To do this, you can:
Choose a method to call based on the command line arguments. The CommandLineParser package from nuget can help here.
Use powershell. Since powershell is based on the CLR, any methods in C # can be accessed from it:
Add-Type -Path путь\к\сборке.dll [Ваш.Класс]::СтатическийМетод(Параметры)The SQL Server Agent can call the built-in powershell script, and the windows scheduler will need a separate file lying on the disk.
You may also have to handle the
AppDomain.AssemblyResolveevent to load dependent assemblies.
You can write your service, which will be running all the time and perform tasks. In this case, the Quartz.NET library may be useful to you . Or you can "roll" your bike (there is a base - just
Task.DelayorTask.Delayin an infinite loop).In any case, the main problem here will be - storing the task list in some permanent storage (DB) or restoring this list when the service starts.
The method with storage in the database is more suitable for tasks created by the user, and the method with recovery at startup is for tasks determined by the application settings.
- Good answer. I will add that it is nice to write services using the Topshelf nuget package. - AK ♦
- @AK Oh, what's so complicated about them all? - Pavel Mayorov