我每天早上从后端Spring-MVC
java应用程序向Android应用程序发送推送通知。为此,我创建了一个 cron job 并在 WebConfig (@EnableScheduling
)中初始化了一个bean。这个bean每天早上都会发送通知。
但如果用户没有阅读,那么我必须在特定时间晚上发送另一个通知。否则我不应该发送任何东西。如何编写 Cron expressen 或计划程序或设置计时器以仅在处发送一次时间,仅在当天?
答案 0 :(得分:2)
仅仅一次启动cron
进程没有多大意义......
模式0 0 hour-minute * * ?
会将任务编程为一小时一分钟,但每天:
0 0 15-45 * * ? // will execute task at 15:45
但要实现这一目标,请查看this answer that shows how to use a Timer to create a thread that runs when needed:
private static class MyTimeTask extends TimerTask
{
public void run()
{
//write your code here
}
}
public static void main(String[] args) {
//the Date and time at which you want to execute
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = dateFormatter .parse("2012-07-06 13:05:45");
//Now create the time and schedule it
Timer timer = new Timer();
timer.schedule(new MyTimeTask(), date);
}
答案 1 :(得分:0)
除了@Jordi Castilla回答之外,我发现此代码有助于仅在特定任务中运行一次所需的时间。
调度任务是指定任务执行的时间。
例如,以下代码计划在11:01 P.M.
//Get the Date corresponding to 11:01:00 pm today.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 1);
calendar.set(Calendar.SECOND, 0);
Date time = calendar.getTime();
timer = new Timer();
timer.schedule(new RemindTask(), time);