This is a creation in Article, where the information may have evolved or changed.
-
- Cause
- Ideas
- Refinement
- Legacy issues
Cause
A lot of times we will encounter such a demand, some time a day to perform a certain task, such as regular mail, timely send push message, and this timing is for local time, such as daily 12 o'clock Noon to send a message to the player to remind players can go online to collect coins.
However, China's 12 points and Vietnam's 12 points are not the same 12 points, so need to pass the time zone to calculate whether the time to perform the task.
Ideas
Let's take a look at how the agreed time is calculated based on the time zone. Suppose you now need 20 o'clock in the evening, perform the task, and the time zone is West 3. First, generate a 20 point of Greenwich Mean
utcTime := time.Now().UTC()targetTime :=time.Date(utcTime.Year(),utcTime.Month(),utcTime.Day(),20, 0, 0, 0, utcTime.Location())
Since the West 3 time zone is 3 hours slower than Greenwich Mean time, and the West 3 time zone 20 points, GMT is 20 points after 3 hours, the corresponding GMT is
targetTime.Unix() + 3 * 3600
And if the East 8 time zone to 20 points, Greenwich Mean time is less than 8 hours to 20 points, then the corresponding times are
targetTime.Unix() - 8 * 3600
Refinement
Define a structure for the refresh time configuration first
typestruct { TargetHour int TargetMinute int Targetsecond int Offset int64 int64}
Defines the time-division seconds of the scheduled task execution, and offset indicates how much offsets can be made on the basis of GMT to achieve local target times. Offset is defined as follows
varZonetooffset =Map[string]Int64{"Z0":0,"E1":-1*3600,"E2":-2*3600,"E3":-3*3600,"E4":-4*3600,"E5":-5*3600,"E6":-6*3600,"E7":-7*3600,"E8":-8*3600,"E9":-9*3600,"E10":-10*3600,"E11":-11*3600,"E12": A*3600,"W1":1*3600,"W2":2*3600,"W3":3*3600,"W4":4*3600,"W5":5*3600,"W6":6*3600,"W7":7*3600,"W8":8*3600,"W9":9*3600,"W10":Ten*3600,"W11": One*3600,"W12": A*3600,}
E8 corresponds to the East 8 district, W3 corresponds to the West 3 district, referring to the previous calculation method.
Calculate whether the local execution time is reached (or exceeded) by the code
funcbool { targetTime := getTargerTime(refreshConfig.TargetHour, refreshConfig.TargetMinute, refreshConfig.Targetsecond, refreshConfig.Offset) return refreshConfig.lastRefreshTime < targetTime && time.Now().Unix() >= targetTime}
After the scheduled task executes, the lastrefreshtime needs to be set to the current time.
Full content view the code on GitHub
Legacy issues
For the calculation of daylight saving time, there is no better way to find out for the time being.