- 论坛徽章:
- 0
|
并非所有的系统中发生的事情都是由用户主动引发的,系统有时候需要根据一定的规则触发相应的时间。其实在jdk1.3,java sdk就通过java.util.Timer提供相应的功能。一个简单的例子说明如何使用,很简单:
1、第一步,我们需要建立一项任务,我们的任务需要继承java.util.TimerTask
package com.danan;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimerTask;
public class TimeTask extends TimerTask {
@Override
public void run() {
//没有秒钟,报告现在的时刻任务
SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月 HH:mm:ss");
System.out.println(sdf.format(new Date()));
}
}
2、我们需要启动我们的任务
package com.danan;
import java.util.Timer;
/**
* @author Administrator
*
*/
public class Hello {
public static void main(String[] args) throws Exception {
Timer timer=new Timer();
timer.schedule(new TimeTask(), 3000, 5000);//注册此任务在第一次运行后的3秒钟时间执行,以后每隔5秒钟时间执行一次。
}
}
schedule(TimerTask task, long delay, long period)中task指定了需要执行的任务,delay指定在第一次运行任务后的多少毫秒执行此任务,period参数指定在以后的多少毫秒执行一次任务。
我们可以看到,很遗憾的是Timer只可以指定多久执行一次,并不能指定在具体那个时间点执行这项任务,比如说我们需要每天午夜1:00执行某一任务,而正是QuartZ调度器起作用的时候了。关于QuartZ的更多信息可以访问
http://www.opensymphony.com/quartz/
,下面让我们来看QuartZ是怎么工作的吧!
创建一项任务
public class Shedule {
//this class do daily task for message awoke and cycle task
public Shedule() {
}
public void say(){
//cycleTask();
messageAwoke();
}
}
package com.danan.action;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
public class DailySay extends QuartzJobBean {
private Shedule sh ;
@Override
protected void executeInternal(JobExecutionContext arg0)
throws JobExecutionException {
sh.say();
}
public Shedule getSh() {
return sh;
}
public void setSh(Shedule sh) {
this.sh = sh;
}
}
我们使用Spring的注入容器注入Shedule;
2、调度cron任务
在Spring配置文件中
bean id="task" class="com.danan.action.Shedule">
property name="hibernateSession" ref="hibernateSession">/property>
/bean>
bean id="job" class="org.springframework.scheduling.quartz.JobDetailBean">
property name="jobClass" value="com.danan.action.DailySay">/property>
property name="jobDataAsMap">
map>
entry key="sh" value-ref="task">/entry>
/map>
/property>
/bean>
bean id="report" class="org.springframework.scheduling.quartz.CronTriggerBean">
property name="jobDetail" ref="job">/property>
property name="cronExpression" value="0 0 1 * * ?">/property>
/bean>
3、启动任务
bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
property name="triggers">
list>
ref bean="report"/>
/list>
/property>
/bean>
这样你将会完成每天凌晨1:00钟启动Shedule 任务的功能.
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/63956/showart_1823922.html |
|