I am working on java TimerTask Scheduler Application. I have main class as Service which is running as Scheduler.
I have TaskSchedule() extends TimerTask class which is used for fixed time execution as:
timer.scheduleAtFixedRate(new TaskSchedule(), ...)
Inside constructor for TaskSchedule I have a dataHelper class which interacts with database for fetching and updating values from database.
In the TaskSchedule class I am overriding run method of TimerTask.
And inside the run method I am calling database helper call with parameters as:
#Override
public void run(){
dataHelper.fetchDataFromDB( ? )
}
Here the question I have placed, where I am stuck in design. I want to keep this parameter to database dynamic.
One Solution I though of is:
Passing database parameter throughout from service to TaskScheduler to dataHelper. But I am looking for better solution on the same at design level.
You can use a shared variable, which you can set outside and also take is before "fetchDataFromDB". You have to care of synchronization. Use a mutex to secure the shared memory.
A another solution is, that you can use somethink like a listener and every time you want to fetch from the db the listener will now it and get the data from you.
Related
One of my Android apps uses a custom Application class to perform some global initialization. This done in the onCreate() method:
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
someCustomInit();
}
}
This works fine, but now I have discovers a crash log in the Developer Console which indicated that MyApplication.onCreate() did not run / has not completed at the time the crash happened: The code crashed because some initialization that is performed MyApplication.onCreate() was not complete.
How is this possible? I assumed that MyApplication.onCreate() would run before all other code? Isn't that correct?
Is it save to move someCustomInit(); to the constructor of MyApplication instead? No other code should run before the application object has been created, correct?
Or are there any side effects from using the constructor instead of onCreate()?
I assumed that MyApplication.onCreate() would run before all other code? Isn't that correct?
ContentProvider instances are created before onCreate() is called on the Application. In theory, your stack trace should show you what code of yours is being invoked prior to your initialization.
Is it save to move someCustomInit(); to the constructor of MyApplication instead?
That would depend on what is happening in someCustomInit(). Your Application is not initialized yet.
Another possibility is to override attachBaseContext(), such as how ACRA is hooked in. There, you are passed a Context object that you can use, if your initialization requires a Context.
The Application class is a singleton for your app process, but its onCreate() is not the first possible code to execute. Class field initializers, the constructor as well as any static code blocks (often used for loading native libs) will execute first. The static code blocks, in particular, will run when the class is loaded by the runtime.
Normally, this is not a problem and your safest route is to put your specific code in the onCreate() method.
How is this possible?
It is possible since Application class onCreate is called for every process of your app.
For example Service can be started in separate process so your Application can be started twice. I have met this behaviour when used Yandex.Appmetrica library. It is not bad actually, because crashes in library will not affect other parts of application.
Or are there any side effects from using the constructor instead of
onCreate()?
From the documentation:
The Application class, or your subclass of the Application class, is
instantiated before any other class when the process for your
application/package is created.
So constructor will be called twice. Any difference?
You should move your code that supposed to run only once to somewhere else, outside Application class. Probably in some Singleton which will be called from Launcher Activity or smth. Actually if you see sources of Application class you will see that comment:
There is normally no need to subclass Application. In most situations,
static singletons can provide the same functionality in a more modular
way.
Is there a way to make my own asynchronous methods on GWT? I am using gwt 2.7 and seems like no java concurrency classes are compatible with gwt.
Here is my story. My client side has a service class, which caches some server data. It has a normal getter method(synchronous) to get the cached data, and it also has a reload method to update the cache.(of course, it is asynchronous). After reload request is sent, the getter method should be disabled until update is done.
Right now, each time I use the getter method, I wrap it inside a timer. It works fine, but I am wondering there is a better way to do it. It is too much boilerplate code.
final AutoProgressMessageBox messageBox =
ServiceManager.createProgressMessage("Progress", "Loading Products...");
Timer timer = new Timer(){
#Override
public void run() {
if(!serviceManager.isProductLocked()){
// already loaded
serviceManager.getProducts();
// do my work...
messageBox.hide();
this.cancel();
}
}
};
timer.scheduleRepeating(2000);
GWT has the Scheduler class, which allows you access some static methods that simulate a multithreaded environment. Specifically, you might be interested in the Scheduler.scheduleFixedPeriod method:
Schedules a repeating command that is scheduled with a constant delay. That is, the next invocation of the command will be scheduled for delayMs milliseconds after the last invocation completes.
I want to schedule some code to be executed in future. What I want to be done in future is that the future process should call a webservice and do something, after that it should call the local database that I have (SQLite) and do some update on it.
I was going to use Handler for this purpose. Wherein I'll pass the Runnable object to it, and inside runnable I'll call AsyncTask to call the webservice, and on the onPostExecute I'll call my local db and do the update.
But the problem is that when I call the db, it is going to require a context to open itself. Now I looked up if I can pass null to it, but then it says that it will create an inmemory database, instead of giving my database that I've created already.
Now, I can pass the context info from the place where I am creating the runnable instance, but what exactly happens if I keep my 'context' object alive. That context is not going to be used anywhere but in the database.
What will be the best way to work this through?
Thanks
Use an IntentService, perform a blocking request so that the service is not killed and then the write to the database both in onHandleIntent.
I think this should work If you use the handler method that you are speaking of. I don't think you will have any issues (other than stopping your garbage collector from collecting the context) if you retain a reference to the context. To be safe though, I would use the application context to create and retrieve the db, as that context doesn't get garbage collected until the android OS kills your app process, which occurs sometime after a user closes the app.
I am trying to get my head around session - timeout - idle handling Multi-treads in Java.
I have a server & client application comunicating via telnet where I need to check if the user has been typing (anything), clicking (anywhere), or moved the mouse within a periode of time.
If not, the user will be prompted with a dialog box, asking if he wants to conntinue session or not. ...(and If not, the user will automatically be logged out within the next minute or so.)
My application has multiple threads. ( - One user per thread). So I am not sure how to approatch this the best (and easiest) way?
I know it is a wide and far-fetched question, but I was hoping some of you could give me a pointer or tip in the right direction... :)
I was kind of hoping for a simple method that could check:
(a bit pseudo code on the fly:)
if (idle = true){
timer.start();
if (timer > 120sec)
displayWaringJFrame("Continue Session? - YES or NO ?)
displayTimer.start();
if (displayTimer > 30sec)
application.user.closeSession()
...or something like that! :)
The simplest solution is a class java.lang.Thread.
You can create class and implements interface Runnable
public class Session implements Runnable{
public void run(){
//your code
}
}
in main function create class Thread and as constuctor argument set instance of Session class after this importatnt is call method .start()
public static void main(String args[]){
new Thread(new Session()).start();
}
Much more convenient way to work with threads is java.util.concurrent.ExecutorService and java.util.concurrent.Executors
Some ideas:
1. if you want a persistent timer you can use a library like Quartz which then you can run a job class you write after a period of time. You can cancel scheduled job, re-schedule etc...
2. You don't necessarily need a thread per user for this to work. A timer object usually has internal threads to handle the workload, either with Quartz or the memory only Java timers.
I have a simple Tomcat 7 Server where I want to implement a Java Web Service which offers some data I can get via my mobile phone.
The point is I want the data on the server being updated every once in a while. So I need a "background process" which updates the data.
I first tried to start a new thread in the constructor of my binding implementation class (which implements only my own Service - not a HttpServlet or so) like
public NewBindingImpl(){
Thread informationFetcher = new InformationFetcher();
informationFetcher.start();
}
But I didn't think about the fact that this class gets created every time someone is using the service. Further more this would update the data only the moment I ask for them. But how could I update them lets say every two hours or so?
Hopefully someone here has an idea. Is that even possible for a "simple" web service?
Thank you very much,
Tobias
EDIT: ----
Maybe it helps to know that I tried this very basic tutorial here:
http://www.elearning.witnut.com/230/java-web-service-creation-using-top-development-approach/
Why not initialise the thread when the servlet's init() method is called ? You can shut it down when the corresponding destroy() method is called. The thread will be bound to the lifecycle of the servlet and since init() is only called once, you won't have to worry about multiple instances.
Here's a brief tutorial on the init() method usage.
Since you want something running every two hours, check out the Timer class. For more complex scenarios Quartz is a serious contender.