2

我每天早上都从后端Java 应用程序向 Android 应用程序发送推送通知。Spring-MVC为此,我创建了一个cron 作业并在WebConfig ( @EnableScheduling)中初始化了一个 bean 。这个 bean 每天早上都会发送通知。

但是如果用户不阅读它,那么只有我必须在晚上特定时间发送另一个通知。否则我不应该发送任何东西。如何编写Cron expressenScheduler设置计时器以在特定时间仅发送一次仅在当天

4

2 回答 2

2

cron只启动一次进程没有多大意义......

Pattern0 0 hour-minute * * ?将编写一个小时和分钟的任务,但每天

0 0 15-45 * * ?    // will execute task at 15:45

但是要实现这一点,请查看此答案,该答案显示了如何使用 Timer 创建一个在需要时运行的线程

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);
}
于 2015-06-15T10:30:31.830 回答
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);

来源: 调度任务就是指定时间

于 2015-06-15T13:35:22.593 回答