2014-03-31 24 views
0

我需要在特定时间每天运行计划任务。在Java中安排某些特定时间?

我有这个至今:

Date timeToRun = new Date(System.currentTimeMillis()); 
Timer myTimer = new Timer(); 

myTimer.schedule(new TimerTask() { 
    public void run() { 
     //Method to run 
    } 
}, timeToRun); 

我将如何设置timeToRun到一个特定的时间呢?这样我就可以在任何特定的日期运行这些代码,并且它可以在正确的时间运行任务;例如每天晚上7:30。

回答

0
import java.util.Timer; 
import java.util.TimerTask; 
import java.util.Calendar; 
import java.util.GregorianCalendar; 
import java.util.Date; 

public final class FetchMail extends TimerTask { 

/** Construct and use a TimerTask and Timer. */ 
public static void main (String... arguments) { 
TimerTask fetchMail = new FetchMail(); 
//perform the task once a day at 4 a.m., starting tomorrow morning 
//(other styles are possible as well) 
Timer timer = new Timer(); 
timer.scheduleAtFixedRate(fetchMail, getTomorrowMorning4am(), fONCE_PER_DAY); 
} 

/** 
* Implements TimerTask's abstract run method. 
*/ 
@Override public void run(){ 
//toy implementation 
System.out.println("Fetching mail..."); 
} 

// PRIVATE 

//expressed in milliseconds 
private final static long fONCE_PER_DAY = 1000*60*60*24; 

private final static int fONE_DAY = 1; 
private final static int fFOUR_AM = 4; 
private final static int fZERO_MINUTES = 0; 

private static Date getTomorrowMorning4am(){ 
Calendar tomorrow = new GregorianCalendar(); 
tomorrow.add(Calendar.DATE, fONE_DAY); 
Calendar result = new GregorianCalendar(
tomorrow.get(Calendar.YEAR), 
tomorrow.get(Calendar.MONTH), 
tomorrow.get(Calendar.DATE), 
fFOUR_AM, 
fZERO_MINUTES 
); 
return result.getTime(); 

} 


} 

在这里,每天凌晨4点执行一​​次任务,从明天上午开始使用Timer和TimerTask。

2

如果你想创建具有特定时间约会对象,这里是代码 -

Calendar cal = Calendar.getInstance(); 
cal.set(Calendar.HOUR_OF_DAY,19); 
cal.set(Calendar.MINUTE,30); 

Date timeoRun = cal.getTime(); 

编辑以适应需求,张贴在评论 -

if(System.currentTimeMillis()>timeToRun.getTime()){ 
    cal.add(Calendar.DATE,1); 
} 
timeToRun = cal.getTime(); 
System.out.println(timeToRun); 

在上面代码,检查当前时间是否大于计算时间,如果是,则增加日期。

+0

这似乎是偶尔为过去设定时间。因此,如果您安排在晚上8点30分的时间,它会在过去30分钟内收集并立即运行。任何想法如何解决这一问题? – user3420034

+0

我已更新代码以符合您的要求 – hellboy

0

这是onliny的说法更

myTimer.schedule(new TimerTask() { 
    public void run() { 
     //Method to run 
    } 
}, timeToRun, 24*60*60*1000); 
0

ScheduledExecutorService的

ScheduledExecutorService接口添加到Java 5的服务于你的目的。

定时器的替代方案。在选择之前,你都应该学习两方面的优点和缺点。

特别提防......

如果任务的任一执行遇到异常,就会取消后续执行。

this humorous post中所述,如果发生任何异常,服务会静默地退出运行更多执行。我使用的一种解决方法是将通用try-catch(和log)运行的整个代码包装为最通用的Exception。

相关问题