我正在使用最新的3.0.6
版本的Quartz.net
我想安排一个每天运行的进程(当前示例是每40秒运行一次,但我会对其进行更改)
我有调用该方法执行的方法,但是在“作业”类中启动该方法时,它似乎并未启动任何应启动的过程。我不确定为什么不触发?
public static void Run()
{
var isRunning = false;
IServiceCollection services = new ServiceCollection();
Startup startup = new Startup();
var serviceProvider = startup.ConfigureServices(services);
IWindsorContainer _container = serviceProvider.GetService<IWindsorContainer>();
while (true)
{
if (!isRunning)
{
isRunning = true;
var configuration = _container.Resolve<IConfigurationRoot>();
var _process = _container.Resolve<Process.Process>();
int secondsForSleep = Convert.ToUInt16(configuration[Enums.SleepTime]);
{
try
{
execute();
}
catch (Exception ex)
{
}
finally
{
isRunning = false;
Thread.Sleep(secondsForSleep);
_container.Release(_process);
}
}
}
}
}
public static async void execute()
{
// construct a scheduler factory
NameValueCollection props = new NameValueCollection
{
{ "quartz.serializer.type", "binary" }
};
StdSchedulerFactory factory = new StdSchedulerFactory(props);
// get a scheduler
IScheduler sched = await factory.GetScheduler();
await sched.Start();
IJobDetail job = JobBuilder.Create<Job>()
.WithIdentity("myJob", "group1")
.Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("myTrigger", "group1")
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInSeconds(1)
.RepeatForever())
.Build();
await sched.ScheduleJob(job, trigger);
}
}
public class Job : IJob
{
public async Task Execute(IJobExecutionContext context)
{
JobKey key = context.JobDetail.Key;
IServiceCollection services = new ServiceCollection();
Startup startup = new Startup();
var serviceProvider = startup.ConfigureServices(services);
IWindsorContainer _container = serviceProvider.GetService<IWindsorContainer>();
var configuration = _container.Resolve<IConfigurationRoot>();
var _process = _container.Resolve<Process.Process>();
Task t = new Task(() =>
{
_process.MainProcess();
});
t.Start();
await t;
}
}
我是否错误地设置了IJobDetail
对象或其他东西?有人有类似的问题吗?看来我确实按照文档做了eryerything,但仍然无法正常工作
答案 0 :(得分:1)
这不是您问题的直接答案,但是如果问题与以下相关,则可能会对您有所帮助。
看,您已经将execute
方法定义为async void
。结果,您无法通过await execute()
调用它,所以
try-catch
块将不处理execute
方法中引发的任何异常finally
块在调用execute()
方法后立即运行(不等待方法完成)换句话说,将您的代码更改为async Task execute()
和await execute()
并再次进行测试。
有关更多理论,建议您阅读以下内容:async/await - when to return a Task vs void?和msdn: Async/Await - Best Practices