[英]Logic for call a function one time only in each 24 hour or in a day in java
i have one function我有一个功能
callEach24hourOneTime();
i have to call this function in each 24 hour only one time within 24 once it will executed then i don't have to call callEach24hourOneTime我必须在每 24 小时内仅在 24 小时内调用一次此函数,一旦它将执行,那么我不必调用 callEach24hourOneTime
i am unable to get current time hour minute and second in millis so that i can apply condition i tried below logic but unable to execute.我无法以毫秒为单位获得当前时间小时分和秒,以便我可以应用我在逻辑下尝试但无法执行的条件。
if(currentmillis=86400000 ){
callEach24hourOneTime();
}
else {
//dont call do other operation
}
please suggest me solution for this .请建议我解决这个问题。
Logic to always have at least 24 hours between executions of the callEach24hourOneTime()
method:在
callEach24hourOneTime()
方法的执行之间始终有至少 24 小时的逻辑:
private long nextCallMillis;
long currentMillis = System.currentTimeMillis();
if (currentMillis >= this.nextCallMillis) {
this.nextCallMillis = currentMillis + 86400000/*24 hours*/;
callEach24hourOneTime();
} else {
// ...
}
That will cause a drift in time-of-day for the execution of the method.这将导致方法执行的时间漂移。 The speed of the drift is determined by how often the code is execute.
漂移的速度取决于代码的执行频率。
If you instead want method to be called at (around) the same time every day :如果您希望每天(大约)同一时间调用方法:
private long nextCallMillis;
long currentMillis = System.currentTimeMillis();
if (this.nextCallMillis == 0)
this.nextCallMillis = currentMillis; // Establish time-of-day
if (currentMillis >= this.nextCallMillis) {
this.nextCallMillis += ((currentMillis - this.nextCallMillis) / 86400000 + 1) * 86400000;
callEach24hourOneTime();
} else {
// ...
}
"Same time every day" is in UTC, so when crossing Daylight Savings Time changes, the time-of-day will change by 1 hour. “每天同一时间”是 UTC,因此当穿越夏令时更改时,一天中的时间将更改 1 小时。
UPDATE更新
If you just want "once per day" logic:如果您只想要“每天一次”的逻辑:
private LocalDate lastCallDate;
LocalDate today = LocalDate.now();
if (! today.equals(lastCallDate)) {
this.lastCallDate = today;
callOnceDailyOneTime();
} else {
// ...
}
You can you a cron library.你可以是一个 cron 库。
I don't really know what language or framework you are currently using, but from spring I'd say you can use @Scheduled :我真的不知道您目前使用的是什么语言或框架,但从春季开始我会说您可以使用 @Scheduled :
@Scheduled(cron = "0 0 0 * * *")
private void myMethod(){}
For exemple the cron above will make myMethod() execute once a day.例如,上面的 cron 将使 myMethod() 每天执行一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.