定时器 Posted on 2018-12-26 | In 亿信华晨 | 定时器的简单应用1234567891011121314151617181920212223242526272829303132333435363738394041424344454647package com.esen.gxdc.test;import static org.quartz.JobBuilder.newJob;import static org.quartz.SimpleScheduleBuilder.simpleSchedule;import static org.quartz.TriggerBuilder.newTrigger;import org.quartz.JobBuilder;import org.quartz.JobDetail;import org.quartz.Scheduler;import org.quartz.Trigger;import org.quartz.impl.StdSchedulerFactory;public class TestQuartz { public static void main(String[] args) throws Exception{ //创建调度器 Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); //定义一个触发器 Trigger trigger = newTrigger().withIdentity("trigger1", "group1") //定义名称和所属的租 .startNow() .withSchedule(simpleSchedule() .withIntervalInSeconds(600) //每隔600秒执行一次 .withRepeatCount(1000)) //总共执行1000次(第一次执行不基数) .build(); //定义一个JobDetail JobDetail job = JobBuilder.newJob(TestSearchSum.class).build(); //指定干活的类MailJob /* .withIdentity("mailjob1", "mailgroup") //定义任务名称和分组 .usingJobData("email", "admin@10086.com") //定义属性*/ //调度加入这个job scheduler.scheduleJob(job, trigger); //启动 scheduler.start(); //等待20秒,让前面的任务都执行完了之后,再关闭调度器 /* Thread.sleep(20000); scheduler.shutdown(true);*/ } private static JobBuilder newJob(Class<TestSearchSum> class1) { // TODO Auto-generated method stub return null; }} #注意插入数据方式因定时器而产生的变化 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647package com.esen.gxdc.test;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.PrintStream;import java.text.SimpleDateFormat;import java.util.Date;import org.quartz.Job;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import com.esen.gxdc.dao.BikeGPSAllDao;import com.esen.gxdc.dao.BikeGPSDao;import com.sun.org.apache.bcel.internal.generic.NEW;public class TestSearchSum implements Job { static PrintStream ps; static{ File log=new File("d:/log.txt"); try { ps = new PrintStream(new FileOutputStream(log)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void execute(JobExecutionContext paramJobExecutionContext) throws JobExecutionException { //File log = new File("d:/log.txt"); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time = df.format(new Date()); int sumBikeAll = BikeGPSAllDao.getInstance().getTotal(); int sumBike = BikeGPSDao.getInstance().getTotal(); String msg = "当前时间" + time + " bileAll总数" + sumBikeAll + " bike总数" + sumBike; ps.println(msg); System.out.println(msg); }}