java 每天运行一次计划任务
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10310411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
run a scheduled task once a day
提问by milind
My requirement is I want to schedule a task that should run once a day.For that I am using following code:
我的要求是我想安排一个应该每天运行一次的任务。为此,我使用以下代码:
public class setAutoReminder {
EscalationDAO escalationDAO=new EscalationDAO();
final SendMail sendMail=new SendMail();
public void fetch(){
Date date=new Date();
Timer timer = new Timer();
timer.schedule(new TimerTask(){
public void run(){
int number=escalationDAO.getAutoReminder();
System.out.println(number);
if(number>0) {
sendMail.sendMail();
}
}
},date, 1000000000);
}
}
but this code runs multiple times.I want it to runs once a day.What should I do?
但这段代码运行多次。我希望它每天运行一次。我该怎么办?
回答by
With Spring (using lombok @Slf4j
):
使用 Spring(使用 lombok @Slf4j
):
@Slf4j
@Component
public class SetAutoReminder
{
@Autowired
private EscalationDAO escalationDAO;
@Autowired
private SendMail sendMail;
@Scheduled(cron = "0 0 0 * * *") // everyday at midnight
public void fetch(){
final int number = escalationDAO.getAutoReminder();
log.debug("Today number: {}", number);
if (number>0) {
sendMail.sendMail();
}
}
}
Tutorial on spring scheduling: springsource blog
spring调度教程:springsource博客
回答by K. Siva Prasad Reddy
If you don't have many scheduled jobs then don't add all the Spring baggage. Keep it simple.
如果你没有很多预定的工作,那么不要添加所有的 Spring 包。把事情简单化。
Date date=new Date();
Timer timer = new Timer();
timer.schedule(new TimerTask(){
public void run(){
System.out.println("Im Running..."+new Date());
}
},date, 24*60*60*1000);//24*60*60*1000 add 24 hours delay between job executions.
This will do the stuff.
这将做的东西。
-Siva
-湿婆
回答by Paul Vargas
You need a scheduler, like Quartz Scheduler
你需要一个调度器,比如Quartz Scheduler