简体   繁体   English

定期在后台运行任务

[英]Run task in background periodically

I want to run some task (fetching data from database) in background after 5 minutes interval. 我想在5分钟间隔后在后台运行一些任务(从数据库中获取数据)。 What should I use? 我应该使用什么?

You can use TimerTask inside a service 您可以在服务中使用TimerTask

 Timer timer = new Timer(); 
 timer.schedule( new YourTask(), 50000 );

Try this. 尝试这个。

  Timer timer = new Timer();
  timer.scheduleAtFixedRate(new TimerTask() {

   @Override
   public void run() {
    //Do something

   }
  }, 0, 5000);

Use Async task: 使用异步任务:

pre Execute, do inBackground, Post Execute 前执行,在后台执行,后执行

With alarm Manager 带警报管理器

Intent myIntent1 = new Intent(sign_in.this,MyNotificationService.class);
                        pendingintent2 = PendingIntent.getService(sign_in.this, 1,myIntent1, 1);
                        AlarmManager alarmManager1 = (AlarmManager) getSystemService(ALARM_SERVICE);
                        Calendar calendar1Notify = Calendar.getInstance();
                        calendar1Notify.setTimeInMillis(System.currentTimeMillis());
                        calendar.add(Calendar.SECOND, 20);

                        alarmManager1.set(AlarmManager.RTC_WAKEUP,calendar1Notify.getTimeInMillis(), pendingintent2);

                        long time = 300*1000;// 5 minutes repeat

 alarmManager1.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar1Notify.getTimeInMillis(),time,pendingintent2);

Add Permission in manifest 在清单中添加权限

    <service android:name="com.example.MyNotificationService" >

        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </service>

you can use a timer task: 您可以使用计时器任务:

TimerTask scanTask;
final Handler handler = new Handler();
Timer t = new Timer();

public void doTask(){

scanTask = new TimerTask() {
        public void run() {
                handler.post(new Runnable() {
                        public void run() {
                            //your task(fetch data)
                        }
               });
        }};

    t.schedule(scanTask, 300000, 300000); 
 }

Please mind that Google ask you to run long operations on Service. 请注意,Google要求您对Service进行长时间操作。 Please read the articles below, to detech what service do you need (service, interservice)! 请阅读以下文章,以对您需要的服务(服务,服务间)进行技术分析!

Intent Service going to shut down itself after the job is done. 作业完成后,意图服务将自行关闭。 To fire a service in every 5mins to do the job , you can combine with a timer, as suggested above. 要每5分钟触发一次服务来完成这项工作,您可以将其与计时器结合使用,如上所述。

Mind before continue: Service belongs to the same thread, where you create it. 继续操作之前请注意:服务属于您在其中创建它的同一线程。 So when you are about to developer your service please use a new Thread to start it. 因此,当您要开发服务时,请使用新的线程来启动它。 If you forget to do it, your service going to belong to the UI thread, mean you are in a trouble.... read first: http://developer.android.com/guide/components/services.html 如果您忘记这样做,那么您的服务将属于UI线程,这意味着您遇到了麻烦。...首先阅读: http : //developer.android.com/guide/components/services.html

developer guide: http://developer.android.com/reference/android/app/Service.html 开发人员指南: http : //developer.android.com/reference/android/app/Service.html

You can use timer, it is not a problem but method within android do have some advantages 您可以使用计时器,这不是问题,但是android中的方法确实具有一些优点

private int mInterval = 5000; // 5 seconds by default, can be changed later
  private Handler mHandler; 

  @Override 
  protected void onCreate(Bundle bundle) {
    ... 
    mHandler = new Handler(); 
  } 

  Runnable mStatusChecker = new Runnable() {
    @Override  
    public void run() { 
      updateStatus(); //this function can change value of mInterval. 
      mHandler.postDelayed(mStatusChecker, mInterval);
    } 
  }; 

  void startRepeatingTask() { 
    mStatusChecker.run(); 
  } 

  void stopRepeatingTask() { 
    mHandler.removeCallbacks(mStatusChecker);
  } 

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

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