How to have a timer running in background to perform an operation after certain periods?

start and stop timer in java example
java run a function after a specific number of seconds
timertask
timer.schedule java
timertask android
how to make a timer in java
java timer(delay)
timertask java 8

I have a button which has a limit of 5 per day and 30 per month. Every time it is clicked it is reduced by 1 from the daily remaining and monthly remaining. Once it has been clicked 5 times, the remaining clicks per day are 0 and he monthly remaining is 25. How do I reset this counter every 24 hours back to 5 in the background, even whilst the app is not running or the device is not turned on. And how do I do the same for after 30 days (month). Currently, I am using SharedPreferences to update the values when I want to. But I want this to happen periodically not every time the app is launched

sharedPreferences.edit().putInt("dailyRemaining", dailyRemaining).apply(); //5
sharedPreferences.edit().putInt("monthlyRemaining", monthlyRemaining).apply(); //30

This is a relatively simple task to do in the background when it can simply be done when the app launches. Implementing and maintaining background tasks in itself is a great deal of work, so if you don't need to do anything in the Background upon a date changing (like sending a notification, or sending that info to a backend, etc.), I would suggest keep it simple and at the UI level. You could do something like this in your main Activity or override your Application class an do it in there):

// Build today date and current month strings which will be used as keys
String todayDate = getDateFromFormat("dd-MM-yyyy");
String currentMonth = getDateFromFormat("MM-yyyy");

// Try to get the remaining limit from sharedpreferences, and give them default
// values if they don't exist yet
int remainingForToday = sharedPreferences.getInt(todayDate, 5);
int remainingThisMonth = sharedPreferences.getInt(currentMonth, 30);

// When the user clicks on the button, decrement and save the remaining 
sharedPreferences.edit().putInt(todayDate, remainingForToday - 1).apply();
sharedPreferences.edit().putInt(currentMonth, remainingThisMonth - 1).apply();

// Utility function to get the date time strings using native Java classes
private String getDateFromFormat(String format) {
    Calendar today = Calendar.getInstance();
    SimpleDateFormat formatter = new SimpleDateFormat(format);
    return formatter.format(today.getTime());
}

What the above is doing is making a key out of todays date, and the current month which would be unique for each day, and each month. Simply check your remaining limits based on that.

Using the Timer and TimerTask Classes, is an example of using a timer to perform a task after a delay: Timer to schedule a task * to execute once 5 seconds have passed. The run method contains the code that performs the task. long period); scheduleAtFixedRate(TimerTask task , long delay, long period); scheduleAtFixedRate(TimerTask task, Date firstTime,� I'm creating a winforms application in visual studio and need a background timer that ticks once every half hour - the purpose of this is to pull down updates from a server. I have tried a couple of different approaches but they have failed, either due to poor tutorial/examples, or to my own shortcomings in C# .

For perform any task after certain periods, you have to refer the android work manager or android job.

Work manager [ https://developer.android.com/topic/libraries/architecture/workmanager ]

Evernote android job [ https://github.com/evernote/android-job ]

Hope it will help you.

Run a background task on a timer, Learn how to schedule a one-time background task, or run a periodic to implement the time triggered background task described in this topic. have a background task that needs to run periodically, or at a specific time. to run every n minutes starting between n and n + 15 minutes after it is registered. If you have an operation that will take a long time to complete, and you do not want to cause delays in your user interface, you can use the BackgroundWorker class to run the operation on another thread. The following code example shows how to run a time-consuming operation in the background. The form has Start and Cancel buttons.

In order to reset values every 24 hours you can use AlarmManager. With it you can schedule execution of service that will reset values in SharedPreferences. But the AlarmManager has it problems, once phone is reboot you have to reschedule it. Don't worry here is the guide that explains how to handle all these things.

Also you can use new WorkManager API. + hand code lab how to use it

Repeating Periodic Tasks, Handler - Execute a Runnable task on the UIThread after an optional delay task in the background as a service; TimerTask - Doesn't run in UIThread and is not Using a Handler , we can execute arbitrary code a single time after a specified delay: .blogspot.in/2013/12/handler-vs-timer-fixed-period-execution. html� Schedule Command Execution Using Timer Overview. The MATLAB ® software includes a timer object that you can use to schedule the execution of MATLAB commands. . This section describes how you can create timer objects, start a timer running, and specify the processing that you want performed when a timer fir

Java Timer TimerTask Example, Java Timer class can be used to schedule a task to be run one-time or to be running the TimerTask, for example if you are creating a Timer to run every 10 complete the task Thread.sleep(20000); } catch (InterruptedException e) { e. schedule() methods to schedule a task to run once at given date or after some delay. Schedule a java task to run at a certain time, and wrap it as a windows service To make a Java program that runs at certain time is not difficult, we can just use java.util.Timer and java.util.TimerTask classes, here is the code.

Timer (Java Platform SE 8 ), A facility for threads to schedule tasks for future execution in a background thread . to each Timer object is a single background thread that is used to execute all of After the last live reference to a Timer object goes away and all outstanding By default, the task execution thread does not run as a daemon thread, so it is� We can use Timer Control in many situations in our development environment. If you want to run some code after a certain interval of time continuously, you can use the Timer control. As well as to start a process at a fixed time schedule, to increase or decrease the speed in an animation graphics with time schedule etc. you can use the Timer

Java.util.Timer Class in Java, Each task may be scheduled to run once or for a repeated number of executions. Each timer object is associated with a background thread that is responsible schedule(TimerTask task, Date firstTime, long period): java.util. long delay) Schedules the specified task for execution after the specified delay On Windows 10, many apps you download from the Microsoft Store will continue to run in the background to take advantage of additional features, such as the ability to download data, update Live

Comments
  • Unifying Background Task Scheduling on Android
  • If the user changes his local date and time, this would effect how everything works?
  • Also how do I convert this to Java, sorry kinda new
  • Also the DateTimeFormatters requires a minimum SDK version of 26 > which is a problem for me
  • First, regardless of what implementation you choose, if you are storing things only locally on the device and not verifying the date through a backend online, yes, the user will be able to change the device date start using the button again. You will need some way to verify the date online to check if it is valid or been changed. If you don't have a backend, I'm sure there are other ways to check it online.It is a very common problem and likely to have been solved.
  • Second, see my updated answer for Java code. And third, my previous code was just to give the concept of getting dates as keys using a library that I usually use in my projects for dates. I have added a code snippet which uses SimpleDateFormat which has been there since the beginning. Have a little search with SimpleDateFormat online to see different ways it can be used in if my provided code doesn't work as it is only stub code which I have written from memory, hopefully it'll work right out the box. Hope it helps.