How to synchronize the time with java calendar - java

How can i synchronize the time (second , hour).
i have this
int minuto = cal.get(Calendar.MINUTE);
int day_Completed = 1440;
but i have no idea how can i do it.
I tried doing this
changing the pc time when a loop is running to see if the var minuto change.
but doesn't work.

An instance of calendar statically reflects one moment in time. It won't get updated automatically, it is not behaving like a clock.
If you want to "synchronize" with the actual time, then you have to
use some sort of timer, maybe based on Thread.sleep for a start
on each "timer event" get the current time (System.currentTimMillis()) and
update the instance of calendar with that value.

Related

How can I know how much time has passed between two operations in my app? [duplicate]

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");

3 days test - upgrading to Pro via In-App Purchase

I'm looking for some ways to make an app that every body can use all the futures for just 3 days, after the limited time ends some of futures disables but again via In-App Purchase they will ready to use.
The question is, How can I set a timer to count down for 3 days from the time that application for first time opened? I should do it in some way that when the phone power offs there mustn't be problem.again after powering on and without opening the app it should count down to 00:00:00.
Is there any samples for this? Or how can I do it?
As #4castle said, set a time stamp when they first open the app. Then, if you want to display a countdown with an exact time until expiration, have a text box somewhere that displays time remaining. Calendar
import java.util.Calendar
if( this.firstTimeRunning() ){
Calendar start = Calendar.getInstance();
//save start.getTimeInMillis()
}
Calendar end = Calendar.getInstance();
end.setTimeInMillis( /* saved millisec value */);
end.set(Calendar.DAY, end.get(Calendar.DAY) + 3);
long difference = end.getTimeInMillis() - start.getTimeInMillis();
text_box.setText(/* format difference*/); //update every second
Something like that.

How to change schedule to a certain time every day insted of every X time

iam trying to make a task to be executed EVERYDAY at 8am (example).
Currently what i have done is make a task, execute it automatically but only for a period of time (in this case 50 seconds) i want it to be executed every day at 8am.
my current code :
Timer time = new Timer();
certif_envia_notificacion st = new certif_envia_notificacion();
time.schedule(st, 0, 50000);
where certif_envia_notificacion is the task that i want to execute, and it does execute every 50 seconds.
Currently the only way i can figure this out is in the task certif_envia_notificacion ask for the time and execute if its 8am, but that seems like a huge waste of server resources, since ill have to execute the task at least 24 times a day.
Thanks in advance.
This is kind of a hack solution that I thought up, but feel free to give comments/feedback based on your requirements.
Basically, from my understanding you have a Java program that runs automatically when the computer starts up (if it restarts), and will then check every hour to see if it is the correct time to run the application. Why not keep it running this way, but instead of running every hour, calculate the time required to get to the next time required (e.g. 8PM the next day).
So for example, lets say you restart it at 3:15PM. When the java program runs, get it to get the current time (System.currentTimeMil...) and then calculate the time required to get to 8PM. You can do some simple math on this (e.g. 20 - current time = time required to wait) and if its negative, simply add 24 to it (e.g. if its 20 - 23, the answer is 24 - 3 = 21, thus wait 21 hours for the next 8PM).
This process can be used every time you run the code, or on startup. I'd recommend just creating a simple function to calculate the required sleep time.
What i finally did was execute the procedure every one hour and make a question of the hour and select the hour that i wanted, i know its not the best way but i needed to finish it fast....
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY);
if(hour == DesiredHour){
//do stuff
}else if(hour == DesiredHour2){
//do stuff 2
}
Thanks for the comments.

AlarmManager Being Triggered immediately because time occurs in the past

When launching my application, the AlarmManager is being triggered immediately because the time occurs in the past.
My idea was to check the actual time with the schedule one :
if(calendar.before(Calendar.getInstance())); //where calendar is my scheduled calendar
If the above condition is true then:
calendar.add(Calendar.DAY_OF_YEAR, 1);
I think this will work.
However the confusion is at day 365:
If the scheduled time was before the Actual time, it will add one day according to this line: calendar.add(Calendar.DAY_OF_YEAR, 1);
and it will become 1
Doesn't that make it always in the past? Because there is no 366 ? Thus the AlarmManager will be always triggering it immediately considering it in the past?
EDIT:
Do you suggest I put instead :
calendar.add(Calendar.HOUR_OF_DAY, 24);
CommonsWare's comment is correct; add() will add that amount of time and adjust all the fields appropriately.
The behavior you were concerned about would occur if you used roll() instead of add(). But you should be safe with add().
Here's the doc if you want to dig in further.

Quartz scheduler and job 'firing' a second early

Can anyone advise? I have a job which runs on the hour, every hour, and which is controlled in a Java webapp by Quartz 1.8.3.
What I'm seeing though is that Quartz seems to start the job a second early sometimes. But as there's no apparent pattern to this it is difficult to correct.
My code is:
Scheduler_Job sj = Scheduler_Job_DB.get(1);
sj.setJobRunning(Valid.TRUE);
Scheduler_Job_DB.update(sj);
SQLDateTime currPollDateTime = SQLDateTime.getSQLDateTimeNow();
Where currDateTimeNow is being set to 17:59:59 when it should be 18:00:00.
The cron trigger for the Quartz job is 0 0 * * * ?
The method SQLDateTime.getSQLDateTimeNow(); simply gets the current count in milliseconds and converts it into java.sql.Date and java.sql.time elements as follows:
public static SQLDateTime getSQLDateTimeNow() {
long milliSecs = DateTime_Utils.getTimeInMilliseconds();
Date date = new Date(milliSecs);
Time time = new Time(milliSecs);
SQLDateTime sqldt = new SQLDateTime(Date.valueOf(date.toString()), Time.valueOf(time.toString()));
return sqldt;
}
Class SQLDateTime simply has two variables as follows:
private Date sqlDate;
private Time sqlTime;
And is convenient when using dates and times stored in the database in yyyy-mm-dd HH:mm:ss format.
In 99.9% of cases this is fine but I don't understand why the job seems to fire one second early?
I should add that upgrading to Quartz 2.x is not an option.
Any ideas anyone?
My solution is to keep it simple. So if the Quartz job fires at a given hour, and if I have the job's details stored in a database table, then I can also store the current run time and date, e.g. YYYY-MM-DD 18:00:00.
So the job fires, it reads the details including the date and time from the database, and makes all the updates for 18:00:00.
Then at the end of the job, the current run time and date get incremented by an hour and are written back to the database for use as the next run date and time. So 18:00:00 becomes 19:00:00 and the date stays the same unless the job is running at 23:00:00.
So everything is in synch and there's no playing with milliseconds.
It sounds good in theory anyway...
It could be that the different clocks are marginally offset, so when the quartz scheduler starts on 18:00:00 005 it could be that the database still thinks its 17:59:59 980.
If its really an issue to you, you might want to sleep the thread some hundred millis so its always correct.

Categories