Search code examples
javaspringcronquartz-schedulerspring-scheduled

How to write a cron expression or Set a timer that will be executed only once in Spring?


I am sending push notifications to android apps everyday morning from backend Spring-MVC java application. For this I have created a cron job and initialized a bean in WebConfig(@EnableScheduling). This bean will send notifications everyday morning.

But if the user don't read it, then only I must send another notification in the evening at particular time. Otherwise I shouldn't send anything. How to write a Cron expressen or Scheduler or Set a timer to send only once at a particular time, only on that day?


Solution

  • In addition to @Jordi Castilla answer, I found this code helpful to run particular task for desired time only once. Scheduling a task is to specify the time when the task should execute. For example, the following code schedules a task for execution at 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);
    

    Source: scheduling a task is to specify the time