I use java.util.Timer to trigger jobs in my app, but I found that it is depend on system time: if system time is adjusted, timer's trigger will be affected.
For example, if system time goes back by 80 seconds, the timer will stop working for 80 seconds.
Java has a System.nanoTime method which is independent of system time, but it seems that it
cannot be used in Timer.
Is there Timer library that supports what I need? Or I have to implement it myself?
Notice that I don't need a precise current time(date), I need a precise time interval
you have 2 options:
Write your one timer, relatively trivial. Before anyone tell reinvent the wheel, being able to carry the task yourself is always important. Especially when it's around 20 lines of code.
Use java.util.concurrent.ScheduledThreadPoolExecturor and use scheduleAtFixedRate, the queue impl. is based on System.nanoTime.
Install ntp daemon that adjusts the time by tuning (slowing down, speeding up) the system clock in very slight fashion during long time span.
Few other things, perfect 100ms is a tall order in non-real time GC environment as GC may STW (stop the world) for seconds sometimes. Sun's GCs can't do that super reliably. IBM's Metronome running on modified Linux kernel is supposed to be able to. You may wish to pay attention to if your application is truly real-time demanding.
If your computer is isolated and off the Internet i think there is not much you can do if the user tampers with the clock.
On the other hand, if this is not the case, you will find quite many API's and Mashups that will allow you to read the correct time. You could read the time from there. You could read the time from time.gov. Also twinsun.com you give you lots of additional options.
100ms seems like too low for Internet time-access.
Related
I'm developing an application where i need to execute a countdown, have a certain counter go down every second, and display in a widget.
No problem, that is done easily using the java class javax.swing.Timer, but the performance are poor.
There are other graphical object on screen and it is not accurate enough, letting it go down from 10 minute to 0 takes more than 10 minutes.
First thing i tried is a Timer with a 1000ms delay, that makes me lose a lot of seconds and sometimes it is not fast enough in updating the view.
Second, i tried with a Timer with a delay of 20ms and a logic inside that let my action run only if the System.nanoTime() report a second from last execution.
This gives me a better accuracy, but yet in an environment where the java application is in execution with other applications on old systems, it performs even worse.
Is there a way to achieve a scheduler indipendent Timer in Java?
I'm up for really anything. OS indipendence isn't really an issue, so native code is an option if it gives me a good result.
UPDATE:
I created an example and uploaded it on gist:
https://gist.github.com/bracco23/c160c9591ac216a2eb9452ef9e7d6d95
Badly, the example isn't really as bad as the full project, i let it run for the full 10 minutes and it took about 602s, a 2s delay that's less than 0.4%, not really bad, i wouldn't mind that.
I'm uploading it to show the schema of the application, the same in the example and in the full application.
thank you very much anyway :D
It has come to my attention that Android 5.1 no longer accepts recurring alarms for time intervals shorter than 60 seconds (source).
I am developing an application that logs information about wireless networks. For the operation of the application it is imperative that it can perform its operations every 1-2 seconds and that it doesn't get killed or suspended by the operating system even if it is using a lot of resources. Reliable operation over long periods of time (several hours) is the most important thing. Impact on battery life is not a concern.
So far the most reliable way of achieving this functionality has been to use recurring alarms. Now with Android 5.1 that is no longer an option. What would be my best options for replacing the AlarmManager implementation?
As a workaround you can set up 60 alarms to get flexible solution for your current implementation. Check OS version and set up as many alarms as you need.
But for a long-term solution I suggest you to implement sticky foreground service which would work similar to music player. Something simple like Handler.postDelayed should be enough to keep it alive. The reason to do this way is that alarms are not accurate and it is always better to have some control on the process.
I've seen a number of questions using the Handler or Timer implementations in Android apps to delay an update to the UI thread. Most of these seem to be short - a few seconds at most.
Are there issues with using a 24 hour delay for a task? How does Android handle very long running Hander and Timers?
Are there issues with using a 24 hour delay for a task?
It won't work reliably.
A Handler, or any other in-process timing option (e.g., ScheduledExecutorService) is only as good as the process that is hosting it. Once the process goes away, so does the timing. Android processes normally do not live for 24 hours.
If it makes you feel any better, all the other alternatives (e.g., AlarmManager, JobScheduler) will also not work reliably as of Android M, in the interests of power management. However, the alternatives will be efficiently unreliable, since they do not require your process to be constantly running.
I know NTP servers can be used to synchronize your computer's system clock. But can NTP be used by an application that wants to schedule things in sync with other systems?
Scenario: Developing a java app (perhaps to run in an ESB like Mule) and you won't necessarily be able to control the time of the machine on which it will run. Can your app use an NTP server to obtain the time and schedule tasks to run based on that time?
Let's say you're using Quartz as the scheduler and perhaps joda-time for handling times (if that's useful). The time doesn't have to be super precise, just want to make sure not ahead of remote systems by much.
If you're not super worried about drift, and assuming that the machines aren't just randomly changing time, then you could ping an NTP server to get what time IT thinks it is, and compare that to the time your local machine thinks that it is, then calculate the differential and finally schedule your task in local time.
So, for example, say that the NTP server says that it's 12:30, but your local machine says that it is 12:25. And you want your task to go off at 13:00 NTP time.
So, 12:25 - 12:30 = -0:05. 13:00 + (-0:05) = 12:55, therefore you schedule your task for 12:55.
Addenda --
I can't speak to the naivety of an implementation, I'm not familiar enough with the protocol.
In the end it comes down to what level of practical accuracy is acceptable to you. NTP is used to synchronize time between systems. One of the problems it solves is by being continually invoked, it prevents clock creep. If you use the "NTP Ping, schedule with offset" technique, and, say, that future time is perhaps 8 hrs in the future, there's a very real possibility of clock creep, meaning that although you wanted the task to go off at "12:55", when 12:55 rolls around, it could be off from the original NTP server since the clocks have not been synced (at all), and the job has not been rescheduled to virtually resync.
Obviously, the longer the period between original schedule and actual execution, the more the potential for drift. This is an artifact no matter how good the original NTP ping is. If you do not plan on rescheduling these tasks as they get close to execution time in order to compensate for drift, then odds are any "reasonable" implementation of NTP will suit.
There's the Apache Commons NET library that has a NTP client. Some complain that it uses System.currentTimeMillis(), which has (had?) resolution issues (10-15ms) on Windows. System.nanoTime addresses this, and you could easily change the library to use that, and rebuild it.
I can't speak to how it reflects the "naivety" of the implementation. But in the end it comes down to how close you need to keep the two machines and their jobs (virtually) in sync.
My intuition tells me that the NTP requires a hardware clock adjustments to keep a pace. So if you don't have access to the hardware, you cannot do it.
However, if it is enough to have a few seconds precision, you could periodically send sample time from a server to calculate a skew between the system clock and adjust scheduled time for jobs.
But can NTP be used by an application that wants to schedule things in sync with other systems?
I've never heard of it being used that way. However, there's nothing to stop you implementing a client for the Network Time Protocol (RFC 1305). A full NTP implementation is probably overkill, but you can also use the protocol in SNTP mode (RFC 2030).
You probably want to set up and use a local NTP server if you want high availability and reasonable accuracy.
A Google search indicates that there are a number of Java NTP clients out there ...
Does the NetBeans CPU Profiler use Wall Clock Time or CPU Time? This is important to know, for example, when thinking about how I/O will be reflected in your profiling results.
The NetBeans default is to use wall clock ("absolute") time for all method timing calculations. A CPU time approach is available, but currently only on Solaris. If CPU time is desired, it can be enabled from the "Advanced settings" area in the "Attach Profiler" window. (The option is called "Use thread CPU timer (Solaris only).")
Regardless of which timer setting is chosen, that setting applies globally to all classes/methods. (For contrast, YourKit allows you to time certain methods using CPU time but other methods using wall clock time.)
Note that, regardless of timer mode, NetBeans does correct its timing info to take into account profiler overhead.
As for I/O: With the default (wall clock) setting, method timings will theoretically include time spent blocking on I/O operations.
More details about the timer options can be found at http://wiki.NetBeans.org/FaqProfilerUsingTimers. I found it helpful to consult that page together with http://wiki.netbeans.org/FaqProfilerSampledInstrumentation, which describes how instrumentation works in both "Exact Call Tree and Timing" mode and "Exact Call Tree, Sampled Timing" mode.