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

3.1k views Asked by At

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?

2

There are 2 answers

0
Chandz On BEST ANSWER

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

9
Jordi Castilla On

That makes no much sense to launch a cron process only for once...

Pattern 0 0 hour-minute * * ? will program task for an hour and minute, but each day:

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

But to achieve this, look at 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);
}