-2

Android studio Java TimerTask don't work at the time i set. I want it to run every 15 minutes in a service class even when application is closed too.

I want it to run every 15 minutes in a service class even when application is closed too. but it works like every hour instead of every 15 minutes

handler = new Handler();
        timer = new Timer();

        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(() -> {
                    if (user.isMining() & checkTime(user.getStopFrom()) < 0) {
                        myRef.update("Balance", FieldValue.increment(0.000001));
                    }else{
                        onDestroy();
                    }
                });
            }
        };

        timer.schedule(timerTask,2000,convert(teamModel.getMultiplier()));
Gökdeniz
  • 1
  • 1
  • 1
  • You need to strip out all the code that is (a) irrelevant to your problem, and (b) meaningless to us readers. And how are we to know what is `convert(teamModel.getMultiplier())`, a key argument in the key method call? Voting to close as unclear and lacking details. Also, this is almost certainly a duplicate of existing questions. – Basil Bourque Mar 25 '23 at 23:03
  • FYI, the `Timer`/`TimerTask` classes have been supplanted by the Executors framework. So noted in [the class API documentation](https://developer.android.com/reference/java/util/Timer). – Basil Bourque Mar 25 '23 at 23:05
  • Executors framework didn't work too :( – Gökdeniz Mar 26 '23 at 14:03

1 Answers1

1

TimerTask won't work when the app is closed. The TimerTask is an object within your app, if your app isn't running, the timer is no longer in memory. If you need to be woken up to do processing every 15 minutes, your options are JobScheduler, WorkManager, or an Alarm. Which of the 3 depends on your usecase.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • Thank you. I tried ScheduledExecutorService but it don't work too. I will try JobScheduler, WorkManager and Alarm. So thank you again. – Gökdeniz Mar 26 '23 at 14:02