简体   繁体   English

如何每天在特定时间触发功能

[英]How to trigger the function every day at a specific time

I am developing and android app. 我正在开发和android应用程序。 This app has several activities. 这个程序有几个活动。 I need the application, regardless of which activity it displays, to execute a query on the server at 2 am every day. 无论应用程序显示什么活动,我都需要每天凌晨2点在服务器上执行查询。 I am currently using Timer and TimerTask, as follows: 我目前正在使用Timer和TimerTask,如下所示:

Timer timer = new Timer();

TimerTask timerTask = new TimerTask() {
            public void run() {
                makePostToServer()
            }
        };

timer.scheduleAtFixedRate(timerTask, getDate(), 1000 * 60 * 60 * 24); // 24 h


private Date getDate() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 1);
        cal.set(Calendar.HOUR_OF_DAY, 2);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);

        return cal.getTime();

}

Is there a chance that for some reason a Timer launched at the start of the application will stop working? 是否有可能由于某种原因在应用程序启动时启动的计时器停止工作? Because the server logs do not always contain information about the executed query. 因为服务器日志并不总是包含有关已执行查询的信息。 It's as if it didn't happen. 好像没有发生。
Maybe there is a better way to call functions every day at 2. 也许有更好的方法每天在2点调用函数。
Best regards 最好的祝福

Instead of this use work manager for your need which is very efficient. 代替此工作经理来满足您的需求,这是非常有效的。 In this case you can use periodic work manager . 在这种情况下,您可以使用定期工作管理器

Check out this for reference. 查看此以供参考。 https://developer.android.com/topic/libraries/architecture/workmanager https://developer.android.com/topic/libraries/architecture/workmanager

Happy Coding!! 快乐编码!

There are several APIs available to schedule tasks in Android: 有几种API可用于安排Android中的任务:

  1. Alarm Manager 警报管理器
  2. Job Scheduler 工作计划
  3. GCM Network Manager GCM网络经理
  4. Firebase Job Dispatcher Firebase作业分派器
  5. Sync Adapter 同步适配器

You can find a lot of sample easily. 您可以轻松找到很多样本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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