c#quartz触发_C#使用Quartz.Net实现定时作业定时任务

在我们平时做开发的时候,时常会用到定时任务触发某个特定逻辑业务以便数据能及时更新

如果你不想用Windows服务, 可以使用Quartz.Net在项目中编写定时任务调度,简简单单几行代码就能搞定。

简介:想要定时抓取、定时更新数据又不想使用windows服务,Quartz.Net组件将会是你最好的选择。

下面来看下Quartz.Net使用方法,下面的DEMO只针对Quartz使用做出详细说明,程序中一些其他逻辑没编写,请自行领悟。

1,将Quartz.dll引用到项目后,先在Web.config中configuration节点中设置定时所需节点

2,编写定时任务,处理定时逻辑

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using Quartz;

namespace PostDatas

{

public class TimeJob : IJob

{

///

/// 将要定时执行的逻辑代码写于此处

/// 此处只做模拟,如需逻辑请自行编写

/// 作者:www.jsons.cn

///

///

public void Execute(IJobExecutionContext context)

{

//将要定时执行的逻辑代码写于此处

PostHelper.HttpPostData();

}

}

}

3,在Global.asax中启动当时任务、处理定时周期等参数

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.SessionState;

using Quartz;

using Quartz.Impl;

namespace PostDatas

{

public class Global : System.Web.HttpApplication

{

///

/// 调用定时任务

/// 作者:www.jsons.cn

///

///

///

protected void Application_Start(object sender, EventArgs e)

{

ISchedulerFactory sf = new StdSchedulerFactory();

IScheduler scheduler = sf.GetScheduler();

IJobDetail job = JobBuilder.Create().WithIdentity("job1", "mygroup").Build();

ITrigger trigger = TriggerBuilder.Create().StartAt(DateTime.Now.AddSeconds(5)).WithCronSchedule("/2 * * ? * *").Build();

scheduler.ScheduleJob(job, trigger);

scheduler.Start();

}

protected void Session_Start(object sender, EventArgs e)

{

}

protected void Application_BeginRequest(object sender, EventArgs e)

{

}

protected void Application_AuthenticateRequest(object sender, EventArgs e)

{

}

protected void Application_Error(object sender, EventArgs e)

{

}

protected void Session_End(object sender, EventArgs e)

{

}

protected void Application_End(object sender, EventArgs e)

{

}

}

}

4,大功告成,只要编写没问题,程序启动后,在设定的时间周期内此定时任务就会按照时间周期去定时触发。

如有不理解的,可以下载DEMO源码体验一下,为了更清晰看到执行周期,请自行添加日志文件记录执行记录。

你可能感兴趣的:(c#quartz触发)