如何写一个cron表达式或设置一个在Spring只执行一次的定时器?
How to write a cron expression or Set a timer that will be executed only once in Spring?
我每天早上从后端 Spring-MVC
java 应用程序发送 推送通知 到 android 应用程序。为此,我创建了一个 cron 作业 并在 WebConfig(@EnableScheduling
) 中初始化了一个 bean。这个bean每天早上都会发送通知。
但如果用户不看,那我只能在晚上的特定时间再发一次通知。否则我不应该发送任何东西。如何编写 Cron expressen 或 Scheduler 或 Set a timer to send only 在特定时间一次,只在那天?
仅启动一次 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);
}
除了 @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);
我每天早上从后端 Spring-MVC
java 应用程序发送 推送通知 到 android 应用程序。为此,我创建了一个 cron 作业 并在 WebConfig(@EnableScheduling
) 中初始化了一个 bean。这个bean每天早上都会发送通知。
但如果用户不看,那我只能在晚上的特定时间再发一次通知。否则我不应该发送任何东西。如何编写 Cron expressen 或 Scheduler 或 Set a timer to send only 在特定时间一次,只在那天?
仅启动一次 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);
}
除了 @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);