如何执行一个任务,每隔一小时? [英] How to execute one task every hour?

查看:243
本文介绍了如何执行一个任务,每隔一小时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在开发一个Android应用程序,我需要执行1任务每隔一小时。我使用下面的code吧:

I have been developing an Android application and I need to execute 1 task every hour. I uses the following code for it:

private static final long ALARM_PERIOD = 1000L;

public static void initAlarmManager(Context context) {

    Editor editor=PreferenceManager.getDefaultSharedPreferences(context).edit();
    editor.putBoolean(context.getString(R.string.terminate_key), true).commit();

    AlarmManager manager = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
    Intent i = new Intent(context, AlarmEventReceiver.class);
    PendingIntent receiver = PendingIntent.getBroadcast(context, 0, i, 0);
    manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime(), ALARM_PERIOD, receiver);
}

这对我的作品,但我的客户告诉我,该任务只能1次,将不能正常工作1小时。我在哪里犯了一个错误?请告诉我。谢谢。

It works for me, but my client tells me that the task works only 1 time and won't work 1 hour. Where have I made a mistake? Please, tell me. Thank you.

推荐答案

根据您的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
}

这篇关于如何执行一个任务,每隔一小时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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