- Таймер — классы Timer и TimerTask
- Запускаем таймер
- Генерируем случайные показания
- Scheduling of tasks with the Android JobScheduler — Tutorial
- 1. Scheduling tasks
- 1.1. Options for scheduling
- 1.2. The job scheduler API
- 1.3. Advantages of the job scheduler API
- 1.4. Create a Job
- Schedule tasks and jobs intelligently in Android
- Problems with Services
- Schedule task in lifetime of your app
- Schedule task outside the lifetime of your app
- Alarm Manager
- Job Scheduler
- GCM Network Manager
- Firebase Job Dispatcher
- Exercise
- Conclusion
Таймер — классы Timer и TimerTask
Классы Timer и TimerTask из пакета java.util позволяют планировать запуск задания на определённое время в будущем. Вы можете создать поток, выполняющий в фоновом режиме и ожидающий заданное время. Когда время истечёт, задача, связанная с этим потоком, будет запущена. С помощью параметров можно запланировать задачу на повторяющий запуск либо на запуск по определённой дате. Вам не нужно создавать поток с помощью класса Thread, так как таймер упрощает эту задачу.
Учитывайте обстоятельство, что таймер выполняется в своём потоке и не должнен задействовать UI-элементы, которые выполняются в своём потоке. Для решения этой проблемы можете использовать метод runOnUiThread() для обновления данных у компонентов.
Классы Timer и TimerTask работают в связке. Класс Timer используется для планирования выполнения задачи. Запланированная к выполнению задача должна быть экземпляром класса TimerTask. Вы сначала создаёте объект класса TimerTask, а затем планируете его запуск с помощью класса Timer.
Класс TimerTask реализует интерфейс Runnable и может быть использован для создания потока выполнения.
В классе TimerTask имеется абстрактный метод run(), который следует переопределить. Метод должен содержать исполняемый код.
Метод cancel() прерывает задание и возвращает значение true, если выполнение задания прервано.
Метод scheduleExecutionTime() возвращает время, на которое последний раз планировался запуск задания.
Как только задача создана, она планируется для выполнения объектом класса Timer.
Методы класса Timer:
- void cancel() — прерывает поток таймера
- int purge() — удаляет прерванные задания из очереди таймера
- void schedule (TimerTask task, long delay) — задание task планируется к выполнению через период в миллисекундах, переданный в параметре delay
- void schedule (TimerTask task, long delay, long period) — задание task планируется к выполнению через период в миллисекундах, переданный в параметре delay. Затем задание повторяется повторно периодически — каждые period миллисекунд
- void schedule (TimerTask task, Date when) — задание task планируется на время, указанное в параметре when
- void schedule(TimerTask task, Date when, long period) — задание task планируется на время, указанное в параметре when. Затем задание выполняется повторно периодически — каждые period миллисекунд
- void scheduleAtFixedRate (TimerTask task, long delay, long period) — задание task планируется к выполнению через период в миллисекундах, переданный в параметре delay. Затем задание выполняется повторно периодически — каждые period миллисекунд. Время каждого повтора задаётся относительно первого запуска.
- void scheduleAtFixedRate (TimerTask task, Date when, long period) — задание task планируется к выполнению на время, указанное в параметре when. Задание затем выполняется повторно периодически — каждые period миллисекунд. Время каждого повтора задаётся относительно первого запуска.
Между методами schedule() и scheduleAtFixedRate() есть небольшая разница, которая заключается в разном поведении, которое зависит от стартовой точки запуска. Так второй метод работает как startTime + iterationNumber * delayTime и помнит время запуска. А обычный метод schedule() помнит последнее время выполнения и работает по формуле lastExecutionTime + delayTime. Для быстрых операций это не сильно отличается, а при ресурсоёмких задач разница будет заметна, например, при работе сборщика мусора приложение может притормозить и следующая задача может запуститься чуть позже.
Как только объект класса Timer создан, запуск планируется вызовом его метода schedule() и его родственника (см. выше).
Запускаем таймер
Напишем простой пример. Подготовим разметку.
Будем использовать два варианта таймера — одиночное и периодическое срабатывание.
Генерируем случайные показания
Допустим нам нужны ежедневные показания термометра. Но мы не можем ждать весь день при написании программ. Поэтому мы можем случайным образом создавать показания с небольшим интервалом и проверить поведение приложения.
Для удобства создадим отдельный класс-утилиту.
Создадим в классе активности метод для генерации значений и вызовем в onCreate().
Источник
Scheduling of tasks with the Android JobScheduler — Tutorial
This tutorial describes how to schedule tasks in Android with the JobScheduler API.
1. Scheduling tasks
1.1. Options for scheduling
If you have a repetitive task in your Android app, you need to consider that activities and services can be terminated by the Android system to free up resources. Therefore you can not rely on standard Java schedule like the TimerTasks class.
The Android system currently has two main means to schedule tasks:
the (outdated) AlarmManager
the JobScheduler API.
Modern Android applications should use the JobScheduler API. Apps can schedule jobs while letting the system optimize based on memory, power, and connectivity conditions.
1.2. The job scheduler API
The Android 5.0 Lollipop (API 21) release introduces a job scheduler API via the JobScheduler class. This API allows to batch jobs when the device has more resources available. In general this API can be used to schedule everything that is not time critical for the user.
1.3. Advantages of the job scheduler API
Compared to a custom SyncAdapter or the alarm manager , the JobScheduler supports batch scheduling of jobs. The Android system can combine jobs so that battery consumption is reduced. JobManager makes handling uploads easier as it handles automatically the unreliability of the network. It also survives application restarts. Here are example when you would use this job scheduler:
Tasks that should be done once the device is connect to a power supply
Tasks that require network access or a Wi-Fi connection.
Task that are not critical or user facing
Tasks that should be running on a regular basis as batch where the timing is not critical
1.4. Create a Job
A unit of work is encapsulated by a JobInfo object. This object specifies the scheduling criteria. The job scheduler allows to consider the state of the device, e.g., if it is idle or if network is available at the moment. Use the JobInfo.Builder class to configure how the scheduled task should run. You can schedule the task to run under specific conditions, such as:
Device is charging
Device is connected to an unmetered network
Start before a certain deadline
Start within a predefined time window, e.g., within the next hour
Start after a minimal delay, e.g., wait a minimum of 10 minutes
These constraints can be combined. For example, you can schedule a job every 20 minutes, whenever the device is connected to an unmetered network. Deadline is a hard constraint, if that expires the job is always scheduled.
To implement a Job, extend the JobService class and implement the onStartJob and onStopJob . If the job fails for some reason, return true from on the onStopJob to restart the job. The onStartJob is performed in the main thread, if you start asynchronous processing in this method, return true otherwise false .
The new JobService must be registered in the Android manifest with the BIND_JOB_SERVICE permission.
Источник
Schedule tasks and jobs intelligently in Android
Jun 1, 2017 · 6 min read
In the modern application development, it is very common for our application to perform tasks asynchronously and scope of them are outside the application’s life-cycle like downloading some data or updating network resources. In some situations we also have to do some work but it is not required to do it right now. To schedule background work, Android introduced several APIs which we can use wisely in our applications.
Selecting a proper scheduler can improve application performance and battery life of the device.
Android M also in t roduced Doze mode to minimize battery drain while user has been away from device for a period of time.
There are several APIs available to schedule tasks in Android:
- Alarm Manager
- Job Scheduler
- GCM Network Manager
- Firebase Job Dispatcher
- Sync Adapter
Problems with Services
Services allows you to perform long-running operations in the background. Running services in the background is very expensive for the battery life of the device.
Services are especially harmful when it continuously uses device resources even when not performing useful tasks. Above problem increased when those background services are listening for different system broadcasts (like CONNECTIVITY_CHANGE or NEW_PICTURE etc.).
Schedule task in lifetime of your app
When application is running and we want to schedule or run a task at a specific time then it is recommended to use Handler class in conjunction with Timer and Thread. Instead of using Alarm Manger, Job Scheduler etc. it is easier and much more efficient to use Handler.
Schedule task outside the lifetime of your app
Alarm Manager
AlarmManager provides access to system-level alarm services. This give a way to perform any operations outside the lifetime of your application. So you can trigger events or actions even when your application is not running. AlarmManager can startup a service in future. It is used to trigger a PendingIntent when alarm goes off.
Registered alarms are retained while the device is asleep (and can optionally wake the device up if they go off during that time), but will be cleared if it is turned off and rebooted.
“We should only use AlarmManager API for tasks that must execute at a specific time. This does not provide more robust execution conditions like device is idle, network is available or charging detect.”
Use Case: Let’s say we want to perform a task after 1 hour or every 1 hour. In this case AlarmManager works perfectly for us. But this API is not suitable in a situations like perform the above task only when network is available or when device is not charging.
Job Scheduler
This is the chief among all the mentioned scheduling options and perform the background work very efficiently. JobScheduler API which was introduced in Android 5.0(API level 21).
This API allows to batch jobs when the device has more resources available or when the right conditions are met. All of the conditions can be defined when you’re creating a job. When the criteria declared are met, the system will execute this job on your application’s JobService. JobScheduler also defers the execution as necessary to comply with Doze mode and App Standby restrictions.
Batching job execution in this fashion allows the device to enter and stay in sleep states longer, preserving battery life. In general this API can be used to schedule everything that is not time critical for the user.
GCM Network Manager
GCM (Google Cloud Messaging) Network Manager has all the schedule features from JobScheduler. GCM Network Manager is also meant for performing repeated or one-off, non-imminent work while keeping battery life in mind.
It is used to support backward compatibility and can also use below Android 5.0 (API level 21). From API level 23 or higher, GCM Network Manager uses the framework’s JobScheduler. GCM Network Manager uses the scheduling engine inside Google Play services so this class will only work if the Google Play services is installed on the device.
Google has strongly recommended for GCM users to upgrade to FCM and instead use Firebase Job Dispatcher for scheduling any tasks.
Firebase Job Dispatcher
The Firebase JobDispatcher is also a library for scheduling background jobs. It is also used to support backward compatibility (below API level 21) and works on all recent versions of Android (API level 9+).
This library will also works when running device do not have Google play services installed and wants to schedule a job in the application. In this condition this library internally uses AlarmManager. If Google Play service is available on the device then it uses the scheduling engine inside Google Play services.
Sync adapters are designed specifically for syncing data between a device and the cloud. It should be only use for this type of task. Syncs could be triggered from data changes in either the cloud or device, or by elapsed time and time of day. The Android system will try to batch outgoing syncs to save battery life and transfers that are unable to run will queue up for transfer at some later time. The system will attempt syncs only when the device is connected to a network.
Wherever possible, it is advised via Google to use JobScheduler, Firebase JobDispatcher, or GCM Network Manager.
In Android N (API level 24), the SyncManager sits on top of the JobScheduler. You should only use the SyncAdapter class if you require the additional functionality that it provides.
Exercise
We discussed lots of theoretical things so now have a look how to use the Android job scheduler.
1. Creating the Job Service
Create JobSchedulerService and extend the JobService class, which requires that two methods be created onStartJob(JobParameters params) and onStopJob(JobParameters params).
The method onStartJob(JobParameters params) gets called when the JobScheduler decides to run your job. The JobService runs on the main thread so any logic needs to be performed should be in a separate thread. Method onStopJob(JobParameters params) gets called if the system determined that you must stop execution of your job even before you’ve had a chance to call jobFinished(JobParameters, boolean).
You also have to register your job service in the AndroidManifest.
2. Create JobInfo object
To construct a JobInfo object, pass the JobService into JobInfo.Builder() as shown below. This job builder allows to set many different options for controlling when job executes.
Now we have JobInfo and JobService so it is time to schedule our job. All we need to do is to schedule a job with desired JobInfo as shown below:
You can download the complete source code of JobSchedulerExample from GitHub.
Conclusion
While scheduling a job, you’ll need to think carefully about when and what should trigger your job and what should happen if it fails for some reason. You have to be very careful with your app performance along with other aspects such as battery life.
JobScheduler is easy to implement and handle most of the complexity for you. While using JobScheduler, our scheduled jobs persists even if system reboots. At this moment the only downside of JobScheduler is that it is only available for api level 21 (Android 5.0).
Thanks for reading. To help others please click ❤ to recommend this article if you found it helpful.
Stay tuned for upcoming articles. For any quires or suggestions, feel free to hit me on Twitter Google+ LinkedIn
Check out my blogger page for more interesting topics on Software development.
Источник