Okay so this might be basic but unfortunately I haven't found anything yet to help with this.
I'd like certain functionality to only happen in Android during a time frame that is specific to UTC/GMT Time.
How do you do this? I tried using System.currentTimeMillis() but if you change the time on an Android Device in the settings, this will also change System.currentTimeMillis().
I'd like to grab a time that is equal to UTC/GMT AND is independent of the Android Device Settings clock, so if the clock is changed on the device it won't interfere.
Any thoughts?
Thanks!
Christopher Steven
time.nist.gov is your friend if you want a truly accurate time.*
String TIME_SERVER = "time.nist.gov";
NTPUDPClient timeClient = new NTPUDPClient();
InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
TimeInfo timeInfo = timeClient.getTime(inetAddress);
NtpV3Packet message = timeInfo.getMessage();
//get the utc long from the server
long serverTime = message.getTransmitTimeStamp().getTime();
(Be sure to bundle all this in a thread if you're running on Android!)
One thing that I like to do is to take the difference between the server time and system time and store that for future use. In short, as long as the system time isn't fiddled with, you don't have to do multiple time calls. You can just take system time and change it based on the difference.
*you will need apache commons for this to work.
You need a time service from Internet. you can get the real time from time server NIST
apache-commons has a TimeInfo class to get NTP date
Example: NTPClient
System.nanoTime() returns the number of nanoseconds since the start up time, and is therefore not be susceptible to system clock changes.
At the startup use:
long startTime = System.TimeInMillis();
long nanoToDeduct = System.nanoTime();
Then at any point in time you can get the current time of the program as the clock was set at the startup of the program with
long currentTime = startTime - timeToDeduct + System.nanoTime();
Related
Is there library in Android that can provide me the total spend time of a user in my application without using my own time count?
I believe that Android OS is counting all application use time the same way as they count battery use ,network, etc..
If my assumptions are right, What I need is this system count for my application use time.
You can use Fabric (https://fabric.io/) there's some a lot useful tools that you can use, it also can track Daily Active User, Crash Reporting, etc.
They also provide us easy integration step, just take few minutes to integrate our system with Fabric.
The general approach to this is to:
Get the time at the start of your benchmark, say at the start of main().
Run your code.
Get the time at the end of your benchmark, say at the end of main().
Subtract the start time from the end time and convert into appropriate units.
A simpler way is this.
long startTime = System.nanoTime();
.....your program....
long endTime = System.nanoTime();
long totalTime = endTime - startTime;
System.out.println(totalTime);
This question already has answers here:
How do I measure time elapsed in Java? [duplicate]
(15 answers)
Closed 5 years ago.
I'm working on an Android app and I have this problem.
For example, if I delete a file (operation A) and I receive a new file (operation B), I want to know how much time has passed between the two operations. I want it to work also if, in between, the user changes the date of the system, turns off the internet or restarts the device.
I know that exists SystemClock.elapsedRealtime() but its value restarts from zero if the user restarts the device.
I cannot use System.currentTimeMillis() because it changes if user changes the date.
I cannot get a date from the internet.
Thanks
Use System.currentTimeMillis(). It gets the time elapsed since the epoch (January 1st 1970).
You need a global var:
long start;
on the first action:
start = System.currentTimeMillis();
Since it's the time from the epoch, restarting the device isn't going to change it (i.e. System.nanoTime would be reset). However, as with most other methods, it isn't safe from changing the time of the device. If someone changes the time on the device back to the start of the epoch, you will experience some problems.
Note that there is no way to get the exact time since the event happened if the time is changed. I.e. if the user does operation A, waits a few hours, sets the clock back to a few hours ago, there's basically no offline ways you can check that. If you use a server, you can get the time from that, but there's not any way to get the accurate, unmodified time difference offline that's tamper proof (where tampering is changing the time).
TL;DR: System.currentTimeMillis is an offline option, but it isn't safe from time changing. If you need it to show the right time difference independently of the user changing the time of the device, use a server.
EDIT:
If you can't use System.currentTimeMillis or get a time from the internet, you can't measure the time at all. AFAIK, every Java/Android API relies on System.currentTimeMillis (or get the current time some other way). Example: the Date class can be converted to a Long representing the current time in milliseconds. For long-term timing, you either have to use System.currentTimeMillis or a server. System.nanoTime restarts when the JVM restarts. So does elapsedRealTime.
You just need to grab the time from somewhere before and after the activities you want to time and take one from the other. This uses the system clock but you could equally get the real time from some other source
long startTime = System.currentTimeMillis();
// Your code
System.out.println("Operation took " + (System.currentTimeMillis() - startTime) + " milliseconds");
I am using freegeoip api to find out country name for each ip, but call limit is 15000 per hour .
How to process each file containing 15000 ips efficiently in an hour.
Is Thread.sleep work?
If they are taking 15 minutes to process, The rudimentary solution is to just take note of the start time. When the process is done, see how many milliseconds is left from the current time until the start time plus one hour.
long startTime = System.currentTimeMillis();
// do the requests
long currentTime = System.currentTimeMillis();
long timePassed = currentTime-startTime;
long millisInHour = 60*60*1000;
long timeToWait = millisInHour - timePassed;
Thread.sleep(timeToWait);
Other things you could consider is Timer.scheduleAtFixedRate() to fire off a file of 15,000 every hour. Better yet, use Quartz or a similar framework to schedule jobs every hour. If running on Linux, you might even schedule the program to run with 1 file every hour using cron. In this case you don't just have a Java process running all the time in the background on your machine.
Another option is to not use freegeoip.net, but use their software which is available here https://github.com/fiorix/freegeoip to then run your own server or integrate the functionality into your program.
I have a simple java program, and I want to know the time difference between some set of operations. For this question the details are not important, but let us take the following scenario.
long beginTime = System.currentTimeMillis();
//Some operations. Let us asssume some database operations etc. which are time consuming.
//
long endTime = System.currentTimeMillis();
long difference = endTime - beginTime;
When the code is run on a machine, how reliable will the difference be?
Let us say, that the processor starts executing some instructions from my code, then gives context to another process, which executes for some time, and then comes back to execute instructions related to this java process.
So, the time difference should depend on the current state of my machine, i.e. how many processes are running etc? So, in profiling time it takes for some operations to run, is this mechanism not reliable?
The granularity of System.currentTimeMillis() depends on the implementation and on the Operating system and is usually around 10 ms.
Instead use the System.nanoTime() which returns the current value of the most precise available system timer, in nanoseconds. Note that you can only use this to calculate elapsed time, you cannot use its value as an absolute time.
Example:
long startTime = System.nanoTime();
// do something you want to measure
long elapsedTimeNs = System.nanoTime() - startTime;
I think your code will do just fine as same is used in several projects. I don't think that if your code calls some other database process etc then it has any effect on your time. It should work fine in that case too.
Ex.
Main Process Started
long beginTime = System.currentTimeMillis();
.
.
.
Called another process (DB or command etc) -> (Another Process start)
.
<Now in this time main process is waiting> .
.
.
Returned from process <- (Another Process end)
.
.
long endTime = System.currentTimeMillis();
long difference = endTime - beginTime;
Now this difference will be total time taken for main process including time taken by another process. THis timing is in reference to the machine of main process & that is fine.
I would like to see how long it takes for a certain method to execute in my android app. My first idea was to do something like this:
Date date1 = new Date();
doStuff();
Date date2 = new Date();
//compare date difference in ms
But for starters, date objects doesnt seem to have a .getMilliseconds(), and thats what im after. Is there any easier and / or better way to solve this?
Thanks
You'll probably want to use System.nanoTime() to do your time counting, as it uses the highest-precision timer available. Another thing to do when testing code efficiency is to not just run it once, but to run it repeatedly, and take the average time as your estimate. This gives better results in the long run, as CPU usage can spike if some other program is also trying to run.
What is wrong with System.currentTimeMillis()?
long before = System.currentTimeMillis();
doStuff();
long after = System.currentTimeMillis();
You could use the Android profiling tools, which can do this kind of stuff in a nice graphical view as the app is running in the emulator.
More info here: http://developer.android.com/tools/debugging/debugging-tracing.html