[英]run a scheduled task once a day
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? 但是这段代码运行了多次。我希望它每天运行一次。我该怎么办?
With Spring (using lombok @Slf4j
): 使用Spring(使用
@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 弹簧调度教程: Springsource博客
If you don't have many scheduled jobs then don't add all the Spring baggage. 如果您没有很多预定的工作,那么不要添加所有的春季行李。 Keep it simple.
把事情简单化。
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 -Siva
您需要一个调度程序,如Quartz Scheduler
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.