将cron表达式从一个时区转换为另一个时区 [英] Convert cron expression from one timezone to another one

查看:841
本文介绍了将cron表达式从一个时区转换为另一个时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种将cron表达式从一个时区转换为另一个时区的方法.

I am looking for a way to convert cron expression from one timezone to another one timezone.

例如,我的Web客户端用户为GMT + 1200,服务器端为GMT + 0800,而用户将02:10设置为在每个星期二和星期四执行任务,则cron表达式将为 0 10 23,5 *?,并且我使用了以下代码,它可以获取用户时区的当前触发时间

For example, my web-client user is GMT+1200 and my server-side is GMT+0800, while user setting 02:10 to execute task every Tuesday and Thursday, the cron expression will be 0 10 2 3,5 * ?, and I have used code as below, it can get current fire time for user's timezone

CronExpression expr = new CronExpression("0 10 2 3,5 * ?");
        
System.out.println(expr.getNextValidTimeAfter(new Date()));
System.out.println(expr.getTimeZone());
System.out.println(expr.getExpressionSummary());
System.out.println("=======");
TimeZone tz = TimeZone.getTimeZone("GMT+1200");
expr.setTimeZone(tz);
System.out.println(expr.getNextValidTimeAfter(new Date()));
System.out.println(expr.getTimeZone());
System.out.println(expr.getExpressionSummary());

getNextValidTimeAfter 将打印 Mon Feb 02 22:10:00 CST 2015 ,该代码在 setTimeZone(tz); 之后,但是 getExpreesionSummary 甚至 getCronExpression()仍将是 0 10 2 3,5 *?,我要获取字符串的位置将是 010 22 2,4 *?,然后我可以将其保存到DB中以备下次火灾使用,也可以将另一个时区用户保存到数据库中以查询设置(当然,这需要转换 0 10 22 2,4 *?到该用户的时区)

The getNextValidTimeAfter will print Mon Feb 02 22:10:00 CST 2015, which after setTimeZone(tz);, however the getExpreesionSummary or even getCronExpression() will still be 0 10 2 3,5 * ?, where I want to get string will be 0 10 22 2,4 * ? and then I can save into DB for next time fire and also another time-zone user to query setting (of course this will need to convert 0 10 22 2,4 * ? to this user's timezone)

感谢您的帮助

推荐答案

如果您愿意保留相同的cron表达式,但根据日期时区进行上下文计算(这样,用户和服务器端将根据其时区来执行下一次执行表达式),则可以使用 cron-utils ,它提供了这种功能.自版本3.1.1起,所有下一个/上一个执行计算都与时区相关.

If you are willing to retain same cron expression, but give contextual calculations based on date timezone (so that user and serverside get next execution based on their timezones for same expression), you may use cron-utils, which provides such functionality. All next/previous execution calculations are contextual to timezone, since release 3.1.1.

他们在文档中提供了一个示例:

They provide an example at the docs:

//Get date for last execution
DateTime now = DateTime.now();
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("* * * * * * *"));
DateTime lastExecution = executionTime.lastExecution(now));

//Get date for next execution
DateTime nextExecution = executionTime.nextExecution(now));

nextExecution值将针对与参考日期相同的时区(现在)进行计算.

nextExecution value will be calculated for same timezone as reference date (now).

这篇关于将cron表达式从一个时区转换为另一个时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆