日期:2014-05-19  浏览次数:20778 次

请教一个java timer定时器实用时问题
我在使用定时器时想动态的根据当前时间去执行程序比如:
9月1号执行一次
9月11号执行一次
9月21号执行一次
当启动服务器时定时器会成功执行,可当我改变时间后就执行不了了。请问下能不能时间改变时,也能够动态取得当前时间,然后当条件满足时也能够执行。

public class ContextListener implements ServletContextListener {

private Timer timer = null;
SimpleDateFormat sdf = new SimpleDateFormat("dd");
String date =sdf.format(new Date());

public ContextListener() { 


public void contextDestroyed(ServletContextEvent arg0) {
timer.cancel();
}

public void contextInitialized(ServletContextEvent arg0) {
timer = new Timer();
if(date.equals("01")||date.equals("20")||date.equals("21")){
timer.schedule(new MyTask(),3000);
System.out.println("执行!");
}
}



public class MyTask extends TimerTask {

@Override
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
String date =sdf.format(new Date());
// TODO Auto-generated method stub
if(date.equals("0920")){
System.out.println("清除十二月下旬客户!");
System.out.println("执行完成!");
}
if (date.equals("0111")) {
System.out.println("清除十二月上旬客户!");
}
if(date.equals("0121")){
System.out.println("清除十二月中旬客户!");
}
System.out.println("执行........");
}

}



------解决方案--------------------
用quartz吧
------解决方案--------------------
Java code
public class MyTask extends TimerTask {
private int []MONTHOFDAY ={1,11,21} ;
private static boolean isRunning = false;

@Override
public void run() {
Calendar cal = Calendar.getInstance(); 
if(!isRunning){
    for(int j=0;j<MONTHOFDAY.length;j++){
    if(MONTHOFDAY[j]==cal.get(Calendar.DAY_OF_MONTH)){
    isRunning = true; 
       ////处理业务
        isRunning = false;

    }
    }

}else{
//dothing
}
}

}

------解决方案--------------------
Java code

public class MyTask extends TimerTask {
private Date d = new Date();

@Override
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("dd");
String date = sdf.format(d);

if(date.equals("01")||date.equals("20")||date.equals("21")){
   SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
   date =sdf.format(new Date());

   if(date.equals("0920")){
}

------解决方案--------------------
Java code

public class MyTask extends TimerTask {
private Date d = new Date();

@Override
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("dd");
String date = sdf.format(d);

if(date.equals("01")||date.equals("20")||date.equals("21")){
   SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
   date =sdf.format(d);

   if(date.equals("0920")){
}