Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elapsedRealtime analogue for Object.wait

I used Object.wait(timeout) in my android app service. But it does not count time spent in "deep sleep mode". I use AlarmManager to wakeup my app periodically, so waking from deep sleep is not the problem. The problem is that wait(60000) not terminates after 100 seconds of deep sleep.

As i read on SystemClock help page, object.wait uses uptimeMillis() method, which stops counting in deep sleep. For my needs it will be better to use elapsedRealtime().

How can i implement an analogue of Object.wait(timeout) but using elapsedRealtime method? Or what can i use instead?


One of the tasks i use this method for is to generate "ping" packet to send via network when no other packets are in queue for some amount of time.

like image 920
Tishka17 Avatar asked Mar 24 '26 00:03

Tishka17


1 Answers

Instead of using plain Object.wait() or Thread.sleep() I would suggest you to use any of the following:

  1. Use a java.util.concurrent.newScheduledThreadPool which gives you ability to schedule a task with fixed interval or delay. Initializing the thread pool with threadCount = 1 gives you a single thread.

  2. Use a java.util.Timer which allows you to schedule TimerTask.

I think 1. is a preferred method.

In case you have specific requirement that you want to plug in your timer object or use a specific or 3rd party timing provider, what you need to do is to write your own scheduler which wraps the ScheduledExecutorService, then convert the time using your own timer or get time from your own timer. Basically you launch a scheduled task on the wrapped service with your own time calculation.

I have a sample of such scheduler in my actor model as below. Take a look at the DefaultScheduler in this package. It might be a bit buggy (I haven't tested it fully yet) but it should give you a good idea.

http://sourceforge.net/p/jalgo/code-0/HEAD/tree/trunk/src/org/as/algo/threading/

like image 66
Alex Suo Avatar answered Mar 26 '26 13:03

Alex Suo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!