Java每天/每周定时执行任务

Java每天定时执行任务

 //计算一天的毫秒数
long dayS = 24 * 60 * 60 * 1000;         
// 每天的08:30:00执行任务
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd '08:30:00'");
// 首次运行时间
Date startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sdf.format(new Date()));        
// 如果已过当天设置时间,修改首次运行时间为明天
if(System.currentTimeMillis() > startTime.getTime()){
	startTime = new Date(startTime.getTime() + dayS);
} 

Timer t = new Timer();      
TimerTask task = new TimerTask(){
@Override
public void run() {
   // 要执行的代码
   System.err.println("xxxxxxxxx");
   }
};
     
// 以每24小时执行一次
t.scheduleAtFixedRate(task, startTime, dayS);

每周定时执行任务,需要计算每周的毫秒数,计算同上方法。

//计算周的毫秒数
long weekS = 24 * 60 * 60 * 1000 * 7;  
// 每天的08:30:00执行任务
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd '08:30:00'");
// 首次运行时间
Date startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sdf.format(new Date()));        
// 如果已过当天设置时间,修改首次运行时间为明天
if(System.currentTimeMillis() > startTime.getTime()){
	startTime = new Date(startTime.getTime() + weekS);
} 

Timer t = new Timer();      
TimerTask task = new TimerTask(){
@Override
public void run() {
   // 要执行的代码
   System.err.println("xxxxxxxxx");
   }
};
     
// 以每24小时执行一次
t.scheduleAtFixedRate(task, startTime, weekS);

你可能感兴趣的:(java开发)