Setting a timezone for quartz simple trigger

2019-07-23 19:01发布

I need to set a quartz trigger for a job that includes a timezone. E.g. I need to set it for 27 August 2012 at 15:00 Europe/Amsterdam timezone. My server works on UTC.

I believe a SimpleTriggeris what I need, but I do not know how to set a timezone for it.

Any idea?

2条回答
时光不老,我们不散
2楼-- · 2019-07-23 19:42

SimpleTrigger's fire time is based on the configured start time.

The start time is specified as a java.util.Date, which is really just time specified in milliseconds since Jan 1, 1970 00:00:00.000 GMT.

If, at Oct 23, 2010 8:13:45 EST your code executes new Date(), and sets the result as the start time, Quartz will store as the start time the value in milliseconds (1287839625000), and then the trigger will fire at Oct 23, 2010 8:13:45 EST regardless of which timezone the scheduler is running in.

If you use java.util.Calendar to define a date and time in a particular time zone, and then convert that to a Date, it will work exactly the same: If you have specified Oct 23, 2010 8:13:45 and the Calendar's time zone is EST then the resulting milliseconds value will again be 1287839625000. But if the timezone was PST (but the date time the same) the milliseconds value would be 1287850425000 (3 hours later).

Just make sure the system clock where Quartz is running has been correctly set and is maintained as UTC by the operating system.

查看更多
叼着烟拽天下
3楼-- · 2019-07-23 19:42

I had the same requirement.I was able to achieve this using following way.

  1. Convert user time to UTC utcTime =userTimetoUTCTime("09/28/2017 12:00:00 AM")
  2. Re convert UTC to server time zone and set it to simple trigger utcTimetoUserTime(utcTime)

    public static String userTimetoUTCTime(String userTime) {

        ZoneId zone = ZoneId.systemDefault();
    
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm:ss a").withZone(zone);
        ZonedDateTime utc = ZonedDateTime.parse(userTime, fmt).withZoneSameInstant(ZoneOffset.UTC);
    
        // Convert Local Time to UTC
        OffsetDateTime gmtTime = utc.toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC);
        // Utc to local time
        // gmtTime.atZoneSameInstant(ZoneId.systemDefault()).toString();
        return gmtTime.toString();
    }
    

public static Date utcTimetoUserTime(String utcTime) { return new DateTime(utcTime).toDate(); }

Note : Can set time zone in CronTrigger but not in SimpleTrigger

查看更多
登录 后发表回答