上次我们了解过了timer的有关内容,这次来了解下另外一个定时器quartz的实现,快来看看吧。
1、首先,在pom.xml中进行最重要也是基础的导包环节
<dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.2.1</version> </dependency> < dependency > <groupId>org.quartz-scheduler</groupId> < artifactId > quartz - jobs < /artifactId> < version > 2.2 .1 < /version> < /dependency>
2、其次,定义需要执行的定时任务类
import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class MyJob implements Job { @Override public void execute(JobExecutionContext arg0) throws JobExecutionException { // TODO Auto-generated method stub System.out.println("开启了定时任务"); } }
3、最后按照定时任务的固定步骤来做就行了:定义调度器并且开启 ;定义任务器 ;定义触发器 ; 注册
import org.quartz.*; import org.quartz.impl.StdSchedulerFactory; public class QuartzDemo { public static void main(String[] args) { try { new QuartzDemo() .quartzTest(); } catch (InterruptedException i) { i.printStackTrace(); } } public void quartzTest() throws InterruptedException { try { //获取调度器 Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); scheduler.start(); //创建任务器:定义任务细节 JobDetail jobDetail = JobBuilder.newJob(MyJob.class) .withIdentity("job1", "group1") .build(); ScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule() .withIntervalInSeconds(5) .repeatForever(); //定义触发器 Trigger trigger = TriggerBuilder.newTrigger() .withIdentity("simpleTrigger", "simpleTriggerGroup") .withSchedule(scheduleBuilder) .startNow() .build(); //将任务和触发器注册到调度器中 scheduler.scheduleJob(jobDetail, trigger); // Thread.sleep(1000*30); } catch (SchedulerException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
以上就是今天的所有内容,更多java程序代码例子敬请关注奇Q工具网了解详情。
推荐阅读: