Schedule a C# console application

2019-01-26 01:24发布

问题:

I've given a task to create an email C# console application which targeted to run as batch. I'm very new to C# area and hence I have no idea about my direction. This C# console application will be deployed on a server and expect to run in certain time based on server time.

After some research, most of the suggestions are about using task scheduler or window services, but I'm wondering if this C# console application is somehow possible to run own its own? Maybe after execute it, it then register itself into the server and the server will handle it periodically?

回答1:

If you want to manage the scheduler by code have a look at Quartz.NET: http://quartznet.sourceforge.net/

This library provides the creation of jobs and triggers.

e.g. (directly from: http://quartznet.sourceforge.net/tutorial/lesson_3.html):

// construct a scheduler factory
ISchedulerFactory schedFact = new StdSchedulerFactory();

// get a scheduler
IScheduler sched = schedFact.GetScheduler();
sched.Start();

// construct job info
JobDetail jobDetail = new JobDetail("myJob", null, typeof(DumbJob));
// fire every hour
Trigger trigger = TriggerUtils.MakeHourlyTrigger();
// start on the next even hour
trigger.StartTime = TriggerUtils.GetEvenHourDate(DateTime.UtcNow);  
trigger.Name = "myTrigger";
sched.ScheduleJob(jobDetail, trigger);

Now this means your console application should run continuously which makes it not really suitable for the job.

Option 1. Add a task via task scheduler (real easy) that executes your console application. See example task: http://www.sevenforums.com/tutorials/12444-task-scheduler-create-new-task.html

Option 2. Create a windows service (not to complicated) that uses a library like Quartz.NET or .NET's Timer class to scheduele jobs and executes a batch operation. See for creation of windows service http://msdn.microsoft.com/en-us/library/zt39148a.aspx

Option 3. Make your console application implement a scheduele library like Quartz.NET or /Net's Timer class and run it as a service (a bit more complex): Create Windows service from executable



回答2:

As long as it requires no user input, it will be able to run on it's own. You can schedule the program to run in Windows Task Scheduler for example.