且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何执行一个任务,每隔一小时?

更新时间:2023-10-23 18:43:40

根据您的code,ALARM_PERIOD为1000L,作为重复间隔。所以我怀疑报警将设置在每1000毫秒。

According to your code, ALARM_PERIOD is 1000L, as repeating interval. So I doubt the alarm will set of in every 1000 milliseconds.

如果您在设置重复间隔时间每隔一小时,它应该是3600000L。 并注意到,如果手机重新启动,你的报警管理器将不再除非你重新开始工作。

if you are setting repeating interval for every hour, it should be 3600000L. And take note that if the phone is restarted, your alarm manager will no longer work unless you start again.

下面是我的code:

private void setAlarmManager() {
    Intent intent = new Intent(this, AlarmReceiver.class);
    PendingIntent sender = PendingIntent.getBroadcast(this, 2, intent, 0);
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    long l = new Date().getTime();
    if (l < new Date().getTime()) {
        l += 86400000; // start at next 24 hour
    }
    am.setRepeating(AlarmManager.RTC_WAKEUP, l, 86400000, sender); // 86400000
}