I need to make sure that after pressing one button, the other is not available for 15 minutes. To do this, I use a method like this:
disposableTimer = Observable.timer(15,TimeUnit.MINUTES)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(aLong -> {
buttonSimpleAct.setEnabled(true);
});
This works well when the program is active, but I need this timer to work even when the program is closed.
That is, if the first button was pressed, the application was closed and returned after 15 minutes, the second button should already be active.
Are there any ways to make the Observable work in the background, or alternatives to this?
What I'd do is save (in a persistent manner) the timestamp for when the button should be re-enabled and restart the timer with the remaining time when the app comes back.
// when the first button is clicked:
long reenableAfter = System.currentTimeMillis() + 15 * 60 * 1000L;
save(reenableAfter);
disposableTimer = Observable.timer(15 ,TimeUnit.MINUTES, AndroidSchedulers.mainThread())
.subscribe(aLong -> buttonSimpleAct.setEnabled(true));
// when the app starts
long reenableAfter = load();
disposableTimer = Observable.timer(reenableAfter - System.currentTimeMillis(),
TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
.subscribe(aLong -> buttonSimpleAct.setEnabled(true));
Related
I would like to use a timer that counts up like: 00:00:00 -> 00:00:01 and so on , I tried it with
Long start = System.currentTimeMillis();
Long end = System.currentTimeMillis() - start;
but didn't worked. This is how i get my data from my localhost. I would like to use this to calculate the timer via my Server , but it doesnt work.
I just would like to see a timer alongside my uploaded file in my client GUI
Hope someone can help, if you have more questions ask me :)
ResponseEntity<String> response = restTemplate.postForEntity(format("http://localhost:8080/file/upload?uid={0}&time={1}", uid , time)
EDIT: This is how my Client JTable looks like Its not my idea but my supervisor just want to see what the average time is that the server needs to run the (.bat) File. And u cant calc how long a (.bat) file needs so i need a timer that counts up.
And i was thinking this should be possible via the server.
Without going into details if it is smart to do a server-side timer for uploads, you can't make a second-step with this
Long start = System.currentTimeMillis();
Long end = System.currentTimeMillis() - start;
because it will just execute at whatever speed your system is running at.
Something like the code below will trigger once every second, but you'll have to run that in its own thread as not to block the main-thread with the while:
while(true){
System.out.printLine("tick");
Thread.sleep(1000);
}
I am working on an reminder type java application using javafx which will remind me about tasks showing pop up on desktop about the task.But i don't know how to do it.Can anyone help me?
The Reminder Notification Mechanism
This assumes using JavaFX 8. The reminder has date and time fields. The app displays an alert dialog (javafx.scene.control.Alert control) whenever a reminder is due.
The notification mechanism is implemented using the Timer and TimerTask API of java.util package. Timer is a facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals. The task is defined by extending a TimerTask. This is an abstract class which implements Runnable; the run() method has code for the action of this task.
There are two tasks defined for reminder notification. The first one is run once at the start of the app; this checks for all the overdue reminders and shows them in reminder alerts. The next task is scheduled to run at a regular interval, every minute (or whatever is the desired time interval) for the duration of the app.
The following code snippet shows the initialization of the timer and timer's task at the start of the app:
Timer timer = new Timer();
RemindersTask tasks = new RemindersTask();
timer.scheduleAtFixedRate(tasks, zeroDelay, periodOneMinute);
The Reminders Task
The class RemindersTask.java extends the TimerTask and overrides the run() abstract method. The run method has code to check for due or overdue reminders and display the reminder alert.
In the following code snippet the getDueRems() method retrieves all the due reminders based on the supplied predicate (of type java.util.function.Predicate). Initially, the predicate value is set as: Predicate<Reminder> predicate = ReminderPredicates.OVER_DUE; - this notifies all the due reminders until the start of the app - all overdue reminders. After the first run of the task, the predicate is reset to ReminderPredicates.DUE_NOW and is run at a regular interval set at the start of the scheduling the timer.
The following code snippet shows the run method for the timer task:
public void run() {
List<Reminder> dueRems = getDueRems();
showNotifications(dueRems); // shows the multiple notifications in an alert dialog
predicate = ReminderPredicates.DUE_NOW;
}
private List<Reminder> getDueRems() {
ObservableList<Reminder> rems = dataClass.getAllReminders();
return rems.stream()
.filter(predicate)
.collect(Collectors.toList());
}
The Reminder Predicates
A java.util.function.Predicate<T> is a functional interface and represents a predicate (a boolean-valued function) of one argument (T is the input type).
Here are some example predicate definitions (defined in ReminderPredicates class as constants), and others may be defined based on the requirements:
Predicate<Reminder> TODAYS = r -> r.getDate().isEqual(LocalDate.now());
Predicate<Reminder> COMPLETED = r -> (r.getCompleted() == true);
Predicate<Reminder> DUE_NOW = TODAYS.and(COMPLETED.negate());
i have code like this , i wanna make timer keep running when i close the app.
private void startStop() {
if (timerStatus == TimerStatus.STOPPED) {
setTimerValues();
setProgressBarValues();
timerStatus = TimerStatus.STARTED; startCountDownTimer();
} else {
timerStatus = TimerStatus.STOPPED;
stopCountDownTimer();
}
}
Assuming you want something like starting the timer, see the progress bar move and if you come back to your app after an hour, it should have advanced by that time.
The easiest approach would be to store the time at which the timer was started in a shared preference and update your timer periodically using System.currentTimeMillis()-startTime
All left to do is restore the shared preference in your Activity's onCreate
If I have not explained this properly please help me to correct my question. My question may be related to Java timer, or it may be related to general problem solving.
Dear reader, you don't need to understand what OpenHAB is, what an OpenHAB rule is, or indeed what MQTT does. But I'll use these terms anyway to set the scene of my question.
In OpenHAB I have a rule that responds to messages published to an MQTT topic. When I turn a light dimmer down, an burst of "down" MQTT messages are sent to a broker. Each message fires an OpenHAB rule which reads the current value of the light and subtracts 1 then writes it back.
To ensure the rule does not fire concurrently in different threads (thus preventing the light from dimming at the correct rate), a colleague of mine recommended I add lock.lock like this:
rule "ArduinoBedroomVector"
when
Item Bedroomvector received update
then
lock.lock()
try {
// rules here
var Number lightcircuit1level = BedroomCeilingLight.state as DecimalType
switch(Bedroomvector.state) {
case "light_1_up" : {
lightcircuit1level = lightcircuit1level + 3
if(lightcircuit1level>100) lightcircuit1level = 100
sendCommand(BedroomCeilingLight, lightcircuit1level);
}
case "light_1_down" : {
lightcircuit1level = lightcircuit1level -3
if(lightcircuit1level<0) lightcircuit1level = 0
sendCommand(BedroomCeilingLight, lightcircuit1level);
}
}
}
finally {
lock.unlock()
}
end
and this worked a treat.
Now my actuator doesn't miss "down" messages.
However because the actuator takes a little while to respond to each individual message (it's running over 433MHz RF transmission, each RF message message takes .5 seconds to send), the dimming commands to the actuator are queuing up.
So I need to introduce a way of checking to see whether the rule ran in the last e.g. 0.6 seconds. If it did, then increment the value, but don't send the command. If it didn't, increment the value and finally send the command.
For example this means I could dim the light up and down continuously and as long as I don't stop, the light level wouldn't change. Then as soon as I decide to stop dimming up or down, the light level will be finalised and set.
Better still a timing "rule" that would allow me to continuously change the level but only set the light level every 0.5 seconds according to what the latest level is.
I'm sure this is just a case of creating a timer which is checked at the time the rule is run, but I can't get my head around when the timer should be created and checked. This is probably blindingly obvious to many people.
Don't be too hard on yourself, it isn't blindingly obvious.
My approach is to keep a timestamp of the most recent execution of the rule and add an if statement before calling sendCommand to check if at least .6 seconds has passed.
However, there is one edge case where if the last receipt of the a command is before the .6 seconds have passed the new value will never be sent so we need to set a timer to get that last value published. But then we need to clean up the timer so it doesn't fire if we received a new command after the timer was set but not yet fired. Edge cases are messy.
var lastExec = now.millis
var Timer timer = null
rule "ArduinoBedroomVector"
when
Item Bedroomvector received update
then
lock.lock()
try {
// rules here
var Number lightcircuit1level = BedroomCeilingLight.state as DecimalType
switch(Bedroomvector.state) {
case "light_1_up" : {
lightcircuit1level = lightcircuit1level + 3
if(lightcircuit1level>100) lightcircuit1level = 100
// Wait to send the new value
}
case "light_1_down" : {
lightcircuit1level = lightcircuit1level -3
if(lightcircuit1level<0) lightcircuit1level = 0
// wait to send the new value
}
}
// if more than .6 seconds have passed since the last time the value was sent
if((now.millis - lastExec) > 600){
// cancel the timer if one is already set
if(timer != null) {
timer.cancel
timer = null
}
sendCommand(BedroomCeilingLight, lightcircuit1level)
lastExec = now.millis
}
// its too soon to send the update, set a timer
else {
// cancel the timer if one is already set
if(timer != null) {
timer.cancel
timer = null
}
// set a timer to go off in what is left of the .6 secs since the last update
var t = now.plusMillis(600) - lastExec
timer = createTimer(now.plusMillis(t), [|
sendCommand(BedroomCeilingLight, lightcircuit1level)
lastExec = now.millis
// beware, there could be a race condition here as the timer
// will execute outside of the lock. If the rule executes
// at the same time as the timer the most recent value of
// lastExec may be overwritten with an older value. It should
// happen very rarely though and may not be a problem.
]
}
}
finally {
lock.unlock()
}
end
I want to auto-schedule a thread with a particular time interval. I also need to execute this in the background continously without hangs to the device.
I have tried this with Application Manager Class but it's for application scheduling and I need to schedule thread within the application.
I would use TimerTask:
public class MyScreen extends MainScreen {
private Timer mTimer;
public MyScreen() {
mTimer = new Timer();
//start after 1 second, repeat every 5 second
mTimer.schedule(mTimerTask, 0, 5000);
}
TimerTask mTimerTask = new TimerTask() {
public void run() {
// some processing here
}
};
}
see BlackBerry API Hidden Gems (Part Two)
use UiApplication.getUiApplication().invokeLater()
it accepts a delay and repeat parameters and will perform exactly what you need.
EDIT
I know this post is old but this is by far the best option to schedule repeating events and I would like to add that to stop the scheduled event the following is required:
//Start repeating "runnable" thread every 10 seconds and save the event ID
int eventId = UiApplication.getUiApplication().invokeLater(runnable, 10000, true);
//Cancel the repetition by the saved ID
UiApplication.getUiApplication().cancelInvokeLater(eventId);
Assuming you want it to run a thread on device startup:
Create a second project and list it as an alternate entry point.
In your UiApplication or Application main(), check the argument passed to the project. Do your periodic stuff there via Thread.sleep and don't call enterEventDispatcher.
search for "autostart":
http://docs.blackberry.com/en/developers/deliverables/1076/development.pdf
Or if you want to do something once a user "starts" it, then look into creating a new thread to do your timing stuff. Override your screen's onClose() and use Application.getActivation().deactivate() to throw the screen into the background.
Or there's a other ways to do something like this like invokeLater, etc. Maybe eventlisteners may do what you need, but you didn't give a lot of details.
As long as the application is running - just create the thread and after each bit of work call Thread.sleep for as long as you need it to stay dormant.
If you need it to wake up at a particular time, rather than just sleep for a particular time, then you can do something like the following:
Date wakeUpAt = ...; // Get this however
Date now = new Date();
long millisToSleepFor = wakeUpAt.getTime() - now.getTime();
Thread.sleep(millisToSleepFor);