我用的是java.util包下的timer类,想实现每天24点执行一段代码,应该怎么设参数啊?
Timer timer = new Timer(true);
timer.schedule(task, firstTime, period)
有好几个schedule方法,我应该用哪个?参数怎么写呢?
Timer timer = new Timer(true);
timer.schedule(task, firstTime, period)
有好几个schedule方法,我应该用哪个?参数怎么写呢?
private static final long serialVersionUID = 1L;
private TimerManager tm = null; public void contextInitialized(ServletContextEvent sce) {
int day,hour,min,sec;
day = 1; hour = 23; min = 59; sec = 59;
tm = new TimerManager(day,hour,min,sec);
} public void contextDestroyed(ServletContextEvent sce) {
tm.destoryTimer();
}
}public class TimerManager {
Timer t = null;
public TimerManager(int day,int hour,int min,int sec) {
time(day,hour,min,sec);
}
public void time(int day,int hour,int min,int sec){
Calendar c = Calendar.getInstance();
//c.set(Calendar.DAY_OF_MONTH,day);
c.set(Calendar.HOUR_OF_DAY,hour);
c.set(Calendar.MINUTE,min);
c.set(Calendar.SECOND,sec);
Date date = c.getTime();
t= new Timer();
MyTask mt = new MyTask();
t.schedule(mt,date,24*60*60*1000);//你这样写就可以了
}
public void destoryTimer(){
t.cancel();
}}public class MyTask extends TimerTask{
public MyTask() {}
public void run() {
//这里写你要执行的代码
System.out.println("这里写你要执行的代码...");
}}
day = 1; hour = 14; min = 0; sec = 0;
timer.schedule(task, firstTime, period)
而应该使用:
timer.scheduleAtFixedRate(task, firstTime, period)
它们之间是有区别的。
/**
* @author troy(J2EE)
* @version 1.0
*/
import java.util.*;
import java.text.*;
public class DoTask {
private final static Timer timer = new Timer();
private static Date firstTime;//任务首次执行时间
private final static long PERIO_TIME=2 * 1000;//任务运行周期: 单位毫秒
public final static Timer getTimer(){
return timer;//获取timer对象的实例
}
public void start() throws Exception{
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
firstTime=sdf.parse("2010-07-26 16:06:10");
timer.scheduleAtFixedRate(new SendMsgTask(),firstTime,PERIO_TIME);//设置定时任务
}
public static void main(String[] args) throws Exception{
new DoTask().start(); //开启任务
}
}
class SendMsgTask extends TimerTask{
private static int i=0;
public void run() {
sendMsg();
}
private void sendMsg() {
i++;
System.out.println("开始执行-- 开始 (第"+i+"次)");
if(i==5){
DoTask.getTimer().cancel();//当执行任务5次后停止--计时器
}
}
}
参见帖子. 执行时间自己设定, 相当于闹钟.
23楼相当牛
所以 我建议LZ 定时器定时跑,如果没跑的话,你可以在后台管理加个链接手动跑下这段代码啊
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("执行定时任务!!!");
} }; Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(day);
/*** 时间自己修改 ***/
calendar.set(year, month, day, 20, 34, 00);
Date date = calendar.getTime();
Timer timer = new Timer();
timer.schedule(task, date,1000);
} public static void main(String[] args) {
showTimer();
}
这种Daily Job、Nightly Builds,个人还是喜欢用OS的任务