Execute task every hours at specific milliseconds Android - android

For my app I need to execute a task every hours but at specific time.
A server return to me a number of millisecond for example : 100ms, so I need to execute a task at :
00:00:00.100
01:00:00.100
02:00:00.100 etc ....
If the number is 3500 for example, I need to execute task at :
00:00:03.500
01:00:03.500
02:00:03.500 etc ...
I know how to run a task every 1 hour with an interval but I don't know how to do it at a specific time. If anyone has a solution :)

If you really need the exact ms (and I really, REALLY doubt that you do) you're out of luck. Android isn't a real time OS, because Linux isn't a real time OS, and doesn't make those assurances. If you just need really close to the time (like exact to the second), AlarmManager.setExactAndAllowWhileIdle will be called even in low power mode. However there is no repeating version of that, so you'll need to implement that yourself if needed. And AlarmManager doesn't persist alarms through reboot, so if you need it you'll have to do that. Finally you have about 10s to execute whatever you need or take appropriate measures like wake locks to do more.
This also requires the schedule exact alarm permission. Read the docs at https://developer.android.com/reference/android/app/AlarmManager#setExactAndAllowWhileIdle(int,%20long,%20android.app.PendingIntent)

Related

When the android app is force stopped and reopened, will WorkManager executes overdue work or startover?

Assume there is a scheduled work like this:
PeriodicWorkRequestBuilder<RefreshAuthWorker>(
repeatInterval = 15L,
repeatIntervalTimeUnit = TimeUnit.MINUTES,
flexTimeInterval = 5L,
flexTimeIntervalUnit = TimeUnit.MINUTES
)
Let's say, At 10th minute, I forcely killed/stopped the app.
Then reopen the app again after 10 mins.
by this time, the existing/killed work is overdue by 5 mins.
Now, What will the WorkManager do?
1.WorkManager respects the missed overdue work and do it immediately and then schedule the next work.
(or)
2.WorkManager ignores the past overdue work and schedules the next work?
This is a very important scenario to me because, let's say I have to refresh a token every 15 mins. But if WorkManager does like said in 1st point then, by the time I reopen the app, the token is already expired 5 mins ago and the next work is going to happen in 15 mins. So, it's a total of 20 mins with an expired token.
Can somebody who knows any idea what will the WorkManager do in such scenario, please help.
You can't do such things with a WorkManager.
Everything might happen if an application is forced stop. It is a problem of the user if he decides to do so. You should not care.
Are you sure you do not mean - clear from recent?
The priority of WM is saving resources like battery and network data. Timing is not a big concern. The idea is that you need some work to be executed for sure at some point. Like you want to upload a picture to a server.
What WorkManager does is - it creates a job in the JobScheduler. The job is executed when all the constraints are satisfied:
You have implicit constraints related to battery saving. You have some amount of resources that you can use based on your Power Bucket level. Also, the device's state is important. You can't predict when these constraints will be satisfied.
Also you have explicit constraints that you set. Like Connectivity, Battery level and in your case: "a period". But is a no period at all. When you have a "period" work on a higher level in the WorkManager - actually it means - many single jobs in the Job Scheduler. And each one of these jobs has the above implicit constraints and your explicit which is called - timing delay. So you see:
You start the work
WM schedules a job in JS with respective constraints
After 15min timing delay is satisfied
No one can tell what is the status of the implicit constraints. The device might be dozing, or you might have used all of your data usage for the last 24 hours or something like this.
5 At some point when all the constraints are satisfied - the Work starts and when it is finished:
6. You have a new job with the same constraints as before. So in theory your "15min period work" might be executed in 24 hours and after that, it might execute the second time in 15 minutes.

Android PeriodicWorkRequest. Which time it will execute?

I created a periodic weekly work manager worker to delete the files my application creates.
WorkManager workManager = WorkManager.getInstance(context);
workManager.cancelAllWorkByTag(workTag);
PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest.Builder(DeleteFileWorker.class, 7, TimeUnit.DAYS).addTag(workTag).build();
workManager.enqueueUniquePeriodicWork(workTag, ExistingPeriodicWorkPolicy.REPLACE, periodicWorkRequest);
Here, I'm telling the worker to run once a week or once each 7 days.
But when is it going to run? Can I control the approximate hour?
My guess is it will run the first time it can when the application starts and the second time will be at the same hour(approximately) and day as the first launch.
Can I configure it to run around 12 AM? It doesn't need to be an exact time.
You can't have strong expectations with WM. Please check here the Constraints section:
https://developer.android.com/topic/libraries/architecture/workmanager/how-to/debugging#use-alb-shell0dumpsys-jobscheduler
Also, let me point one thing - what you have "is not" a periodic Work.
What WM does is that it creates a single job in the JobScheduler and it has an extra Constrain - TIMING_DELAY. At the same time besides explicit constraints, you have implicit ones coming from the system. So for a work to be executed all the right conditions need to be in places related to battery optimizations, doze, power buckets, etc. So you can't say for sure when it will happen.
And when the work is executed successfully - WM creates a new job in the JS with TIMING_DELAY again the time you see as a period. So if you put 24 hours as a "period", but the conditions are not right for your work to be executed and it is delayed 10 hours - you will have a 34 hours span between 2 works.
Also, you know it is Android - on every device it is different. But you can improve this by asking your application to be excluded from battery optimization.
https://developer.android.com/training/monitoring-device-state/doze-standby#support_for_other_use_cases
Here more on what to expect from each device:
https://dontkillmyapp.com/
Also, have it in mind that you have a specific amount of time depending on your power bucket to run per day. I guess you are not using Network, but if you do - there is also a set amount of time to use the network. Without battery optimization disabled you might hit some of these:
https://developer.android.com/topic/performance/power/power-details

Background accumulated tasks executed periodically

I am devolping an Android App that need to execute an accumulation of internet tasks periodically (like a web bot). Those tasks need to get stored at a specific time so I thought about using Alarm Manager and a
embeded Database. Due to it, the app could be active much more time, although those save tasks do not need web connection. Later I will throw another Alarm Manager to execute all the tasks queued and do web stuff.
Otherwise I am not sure if it is better to use a foreground service. The app will be working all the day saving the tasks (each 5 or 15 min) but only running task queue with internet each 30mins.
I feel capable of developing both systems but I would like to know which one is better in terms of performance, of battery consumption.
Thank you very much.
Only a recommendation try to find and use a nice library to do it, every Android Update change something about foreground/background servicess.
one is
TimedDog
and for more
enter link description here

Intelligent widget update (not in regular intervals)

Well, i've interesting problem. I have a widget, something like reminder, which shows few nearest items on screen. Each item time, when it comes. I need to show only items, which are in the future, not passed items. As regular update can be done at least every 30 minutes, its not enough for me (my items has tiems like 11.54, 12.07, etc). So i have only 1 option = schedule an service, which can update screen in any interval i want (for example every 5 minute).
But this is not very good for me, because i have 2 requirements, which are a little bit fighting together:
run very often (<5 minutes)
do not use too much of battery and other resources
So - is it possible something like intelligent update? I mean for example algorithm like:
a) update screen every 1 minute when device is unlocked (=user is doing something with phone)
b) but do not update when device is sleeping (its useless, as user can't see result of update)?
Or at least something like "run every 5 minutes, but only from 8:00am to 8:00pm during working days"? Simple intelligent service scheduling...
So i have only 1 option = schedule an service, which can update screen in any interval i want (for example every 5 minute).
There are other, more efficient options, like AlarmManager.
is it possible something like intelligent update? I mean for example algorithm like
An intelligent algorithm would recognize the fact that you only need to update the app widget when the list changes, not every minute, second, or millisecond.
Use AlarmManager to set an alarm for one minute past the first item on your list. When you get control from the alarm event, update the app widget, then use AlarmManager to set an alarm for one minute past the next time on your list. Also update your app widget when the list changes from other sources (e.g., UI, sync process), and if that might cause you to need an earlier alarm, cancel your current alarm and schedule a new one using AlarmManager.

How to loop or to repeat periodically task in Android?

I am quite new to Android, and I am really wondering about is how to loop or to repeat periodically a task.
In my program, I have UpdateLoc() that sends my gps location to my databse, but I want it to update periodically (whether it be 3 min or 3 hours) without using too much battery and CPU.
The problem is that I have no idea where to start... Is there a simple way to do this?
You might want to look here:
http://developer.android.com/reference/android/location/LocationListener.html
http://developer.android.com/reference/android/location/LocationManager.html#requestLocationUpdates(java.lang.String, long, float, android.location.LocationListener)
This will allow you to receive updates only after a particular amount of time has past.
I believe you have two options in this case:
Service - This will stay running in the background but use more battery.
AlarmManager - You can schedule a task to run in the future to briefly perform an update operation and should use less battery.

Categories

Resources