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));
}
}
-----------------------