java定时任务配置文件_Java 之使用quartz-1.5.1.jar实现定时任务(在代码中实现不用写配置文件)...

1.需要的jar包

实现定时任务 需要quartz-1.5.1.jar和commons-logging-1.1.jar。

2.定义定时任务配置类

该类主要进行定时任务时间的设置和设置对应的定时任务类。

例子如下:

import org.quartz.CronTrigger;

import org.quartz.JobDetail;

import org.quartz.Scheduler;

import org.quartz.impl.StdSchedulerFactory;

public class Test{

/**

* 定时任务

*/

public static void cleanUpJob() {

try {

JobDetail jobDetail = new JobDetail();

jobDetail.setName("cleanup");

jobDetail.setJobClass(PrintJob.class);

CronTrigger trigger = new CronTrigger();

trigger.setName("cleanupTrigger");

trigger.setJobName("cleanup");

trigger.setCronExpression("0/5 * * * * ?");

Scheduler sch = StdSchedulerFactory.getDefaultScheduler();

sch.scheduleJob(jobDetail, trigger);

sch.start();

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* 修改定时任务时间

*/

public static void modifyJobTime(String triggerName, String time) {

System.out.println("modify~~~~~~~~~~~~~~~~");

try {

Scheduler sched = StdSchedulerFactory.getDefaultScheduler();

System.out.println("triggerName " + triggerName);

CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerName, Scheduler.DEFAULT_GROUP);

if(trigger == null) {

return;

}

String oldTime = trigger.getCronExpression();

System.out.println("oldTime " + oldTime);

if (!oldTime.equalsIgnoreCase(time)) {

System.out.println("time " + time);

// 修改时间

trigger.setCronExpression(time);

}

} catch (Exception e) {

e.printStackTrace();

throw new RuntimeException(e);

}

}

public static void main(String[] args) {

cleanUpJob();

modifyJobTime("cleanupTrigger", "0/2 * * * * ?");

}

}

3.定时任务类

该类主要定义定时任务执行的内容。

import java.text.SimpleDateFormat;

import java.util.Date;

import org.quartz.Job;

import org.quartz.JobExecutionContext;

import org.quartz.JobExecutionException;

public class PrintJob implements Job{

@Override

public void execute(JobExecutionContext arg0) throws JobExecutionException {

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

String time = sdf.format(new Date());

System.out.println("print job" + time);

}

}

4.输出结果

modify~~~~~~~~~~~~~~~~

triggerName  cleanupTrigger

oldTime   0/5 * * * * ?

time   0/2 * * * * ?

print job2014-12-03 17:06:40.031

print job2014-12-03 17:06:42.015

print job2014-12-03 17:06:44.016

print job2014-12-03 17:06:46.019

print job2014-12-03 17:06:48.019

print job2014-12-03 17:06:50.020

从输出的结果中可以看到,原本的定时任务为每5秒执行一次,但是由于后面对定时任务表达式做了修改,所以后来安照修改后的每2秒执行一次。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值