简体   繁体   中英

Java Spring do scheduled task at a specific time of specific timezone

I'm developing a website with Spring and Hibernate (the website is about stock trading).

At about 12 AM everyday, I need to cancel all orders. Currently my solution is using a scheduled task that runs every hour:

 <task:scheduled ref="ordersController" method="timeoutCancelAllOrders" fixed-delay="60*60*1000" />

Then in the method timeoutCancelAllOrders, I get the current time and check, if it's between 11PM and 12AM then do the task

The way I see it, task schedule starts when I start the Server ( I'm using Tomcat in Eclipse), but when I deploy it on an online hosting ( I'm using Openshift), I have no idea when is the starting time of task schedule.

My question is:

1: How to do it more automatic ? Is there anything like myTask.startAt(12AM) ?

2: I'm living in Vietnam but the server (Openshift) is located in US, so here's how I do the check :

        Date currentTime = new Date();
    DateFormat vnTime = new SimpleDateFormat("hh:mm:ss MM/dd/yyyy ");
    vnTime.setTimeZone(TimeZone.getTimeZone("Asia/Ho_Chi_Minh"));

    String vietnamCurrentTime = vnTime.format(currentTime);
    String currentHourInVietnam = vietnamCurrentTime.substring(0, 2);
    System.out.println(currentHourInVietnam);

    if(currentHourInVietnam.equals("00")){
        // DO MY TASK HERE
    }

That looks stupid. How can I improve my code ?

Use a CRON specification :

<task:scheduled ref="beanC" method="methodC" cron="0 0 0 * * ?"/>

Run at midnight every day.

If you instead annotate your method , you can specify the time zone:

@Scheduled(cron="0 0 0 * * ?", zone="Asia/Ho_Chi_Minh")
public void methodC() {
    // code
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM