web 项目quartz集成

web.xml中添加

<listener>
  <listener-class>
  Listener.QuartzSchedulerListener
  </listener-class>
  </listener>

--------------------------

package Listener;


import java.text.ParseException;
import java.util.Map;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.TriggerUtils;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.scheduling.quartz.SimpleTriggerBean;


import Quartz.SchedulerJob;
import Quartz.SchedulerTask;


public class QuartzSchedulerListener implements ServletContextListener {
public void contextDestroyed(ServletContextEvent arg0) {
//
}


public void contextInitialized(ServletContextEvent arg0) {
SchedulerTask task = new SchedulerTask();
// specify your sceduler task details
JobDetail job = new JobDetail();
job.setName("jobName");
job.setJobClass(SchedulerJob.class);
Map dataMap = job.getJobDataMap();
dataMap.put("schedulerTask", task);
try {
// 这部分是每1秒钟执行,无法使用毫秒
/* CronTrigger trigger = new CronTrigger();
trigger.setName("runMeJobTesting");
trigger.setCronExpression("0/1 * * * * ?");// 此处设置计划任务时间
*/
//这种形式支持毫秒
long repeatInterval = 50;//毫秒 =0.05秒
Trigger trigger = TriggerUtils.makeImmediateTrigger(SimpleTrigger.REPEAT_INDEFINITELY, repeatInterval);
trigger.setName("runFirstJobTrigger");
// schedule it
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(job, trigger);


} catch (SchedulerException e) {
e.printStackTrace();
}
}
}

----------------------

package Quartz;


import java.util.Map;


import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;


public class SchedulerJob implements Job {
public void execute(JobExecutionContext context) throws JobExecutionException {
Map dataMap = context.getJobDetail().getJobDataMap();
SchedulerTask task = (SchedulerTask) dataMap.get("schedulerTask");
task.printSchedulerMessage();
}
}

--------------------

要执行的任务

package Quartz;


import java.util.Date;


import org.apache.commons.lang.time.DateUtils;


import com.ace.portsoft.util.MyDateUtils;


public class SchedulerTask {
public void printSchedulerMessage() {
String pattern = "yyyy/MM/dd HH:mm:ss SSS";
System.out.println("Struts 2 + Quartz ......execute Time:"+MyDateUtils.getCurrentDateTime(pattern));


}
}

-----------------------


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值