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);
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
So I am trying to do a chat type program using JavaFX for the GUI. I have it so a class that acts as a server will loop and keep adding client connections to it.
public void serverconnection()
{
// portnumber was saved from constructor
try (ServerSocket socket = new ServerSocket(this.portnumber))
{
// loop is a bool set to true
while (loop)
{
// this class extends Thread and has its own overwritten start method
new myclass(socket.accept()).start();
}
}
catch (IOException e)
{
System.exit(404);
}
}
so the problem is (I am assuming) was, this loop keeps looping until the program closes. but since I was calling this within the JavaFX's initialize method
public void initialize(URL url, ResourceBundle rb)
{
// constructor, nothing here is needed for this post
myclass z = new myclass(45234);
// problem here, since this has a loop, but
z.serverconnection();
// gui wont load till after this is done
// but serverconnection is only done after program ends
}
the problem with this is, apparently, the GUI will not load until AFTER initialize has finished, but it will not finish until program closes. After google searching, I could not find any fix for this. I need a way to call a method that will do all this, AFTER initialize method has finished. My client side class is similar to this, but the methods to connect on that are activated on events when clicking a login button. For this serverside one, I am trying to start without any interaction with the user. so is there a way to call a method or make this work AFTER initialize method has ran?
You might want to run this loop in a thread, so do something like
Thread t = new Thread(z::serverconnection)
t.start()
If you do this at the end of your initialization() method, it will run exactly then.
This will start a thread which runs forever; you might want to add a feature for interrupting the thread when the program is supposed to be terminated.
Remember that for changing anything in the GUI you need to sumbit a task via Platform.runLater(). This is because the GUI may only be modified from within that one thread. So in order to modify anything, you have to wrap that in a Runnable and submit it for execution.
You can do that in this way:
Platform.runLater(new Runnable() {
#Override
public void run() {
doWhateverNeedsToBeDone();
}
});
In Java 8, you can do anything of the following, depending on the extent of the work to be done:
Platform.runLater(() -> {
doWhateverNeedsToBeDone();
});
Platform.runLater(() -> doWhateverNeedsToBeDone());
Platform.runLater(this::doWhateverNeedsToBeDone);
The latter only works if doWhateverNeedsToBeDone() is a method of this.
I am executing several SQL queries in the function evoked by a button in java. I wish to show the status of the same, and I am using a jProgressBar for the same. But the problem is it will only update after the button has finished executing itself, making it pointless to show the progress. How can I display the actual progress of the executing button.
Make a thread dispatcher like this
public class ThreadDispatcher implements Runnable {
public ThreadDispatcher() {
}
public void run() {
//call the method related to query here
}
}
When button pressed call this class and let this class evoke your query related function.
It may be like this when you press the button.
Thread thread = new Thread(new ThreadDispatcher());
thread.start();
sleep(100);
catch the InterruptedException ex.
Link for Thread example
You need to do the computation on a background thread, not the main thread.
Take a look at the Java SwingWorker Tutorial.