Task scheduling for multiple tasks in java? - java

i have build a java clock with using timer,which works fine for a single task to alarm on next given/setted time, but i am having problem in scheduling multiple tasks(alarms for diff. times) with this timer, as two times can clash each other(same times for two different works) how to synchronize between such conditions, please help....
Thanks and Regards
Alok Sharma

I'm not sure what you're trying to do, but if you use quartz scheduler, you can resolve just about any scheduling/synchronisation task:
http://www.quartz-scheduler.org/

I agree with Lukas that you can use quartz. It is the best, scalable and robust solution.
But if you need something relatively small you can continue using timer based solution. As javadoc of Timer class indicates your tasks should take very few time. In this case you can forget about time clash. If your tasks take more then 0.1 seconds run them in separate thread. I mean use Timer as a trigger that just makes task to start in separate thread.
The thread may be done as following:
Create thread yourself. If you are in J2EE container it is bad practice. If you are in Tomcat it is ... not so bad.
Use thread pool. Comments about container are relevant here too.
Use JMS: Timer just pushes message to JMS. MDB or its equivalent receives message and performs task.
Using Timer itsef in J2EE container is a bad practice too. If you are there and wish to be "clean" use JCA to to run Timer.

Related

Prevent time consuming threads to delay more important processes in Android

I have several threads in my Android application that should be executed concurrently. I am not running them on several cores. REAL parallel execution at exactly the same time is not necessary. If Android switches between the different tasks or temporarily pauses certain threads, it's Ok.
The problem: Some threads are highly time consuming and computationally expensive (complex algorithms), but are not real time critical. Other threads and the Android UI thread are real time critical and should not be blocked or heavily delayed by the time consuming processes. Nevertheless, the time consuming processes should also be executed if there are no other more important tasks to perform. Ideally, the highly important threads should safely pause the less important threads. In Java people used to implement suspend() commands, but they are now depricated.
What is the recommended way to solve this problem in Android?? In Java I would have used Sleep commands or wait and notify methods. What is recommended way in Android?
Thanks for the anwer, guys!
Edit:
I was thinking about threads. But I wrote "processes" instead of "threads", just in case regular threads are not the best way to solve the problem in Android. I am open to anything. I have only ONE App. Sorry if terms get mixed up a little. But I wanted to keep the options and ideas open.
Thanks for the comments and answers so far. But I am more interested in a GENERAL, recommended, established strategy and good practice to solve this kind of problem in Android. I could also do some hacks, but I was really hoping for a clean and established solution. I am more looking for an answer like: "The common, established approach is to use strategy A + strategy B..."
In my opinion you should use a different component (Service) and set it to run on a different process - here you can see how
By doing so you can put all the computing in a different process that not related to your man UI component lifecycle.
If the dependency of algorithms' logics and the main UI is loose I wouldn't try to implement them via Threads concurrency.

create multithreaded java ee

Is it possible to create a multithreaded Java EE Glassfish container?
My intention is to create an application where users can capture data launch a social network, then each user would launch a new thread with the parameters he wants to retrieve information from the social network.
all these threads would be limited in number to avoid memory server.
As I can create multiple threads in java ee and that these once the user exits the application to remain running in the background until the user closes them?
One solution may be the job of glassfish?
Your question is pretty broad, but in general I understand you need to execute a thread for each user, which runs in background even when user stops using the application (logs out), does some repetitive task, and is terminated by user when required.
First, I would point out that this can be accomplished in cleaner way using timer service - you can schedule a periodical background job, which will do everyting you need. It can read the list of user and their tasks, perform them at a given interval. Then, a user may request to cance their tasks - they will remove their task from the list.
In this way, the number of users having the background task running would not be limited. They also can run sequentially in a single thread, but you may tweak that, see the rest of my answer.
More into on shceduling a timer in Java EE tutorial: https://docs.oracle.com/javaee/7/tutorial/ejb-basicexamples004.htm.
In case you really need a separate thread per user, there are several ways how to execute a thread separately from the request-handling thread. You might use asynchronous EJB method invocation, using #Asynchronous annotation. You may also inject ManagedExecutorService and use it to execute a Runnable asynchrnously using submit method. In both ways, you would not loose context and dependency injection will continue to work.
See more details about asynchronous eecution in Java EE tutorial about Concurrency utilities
You may also execute runnables asynchronously from a timer, but you may not need that, if you execute only a single task from within a timer handler, as timer handler will be executed when timer triggers in a new thread, if the previous handler did not complete yet.

Multiple SwingWorkers with ExecuterService does not work properly

I am using swing and in my application i needed to run many threads in parallel like checking the internet connectivity after every 5 secs, monitoring the filesystem changes, sycing files from server.
All the time consuming tasks like above are running in SwingWorker so that my GUI should not freeze.
Same time i need to run some other time consuming tasks such as uploading file to server. for this purpose i also used swingWorker. and then i submit all these swingworker to executerService for thread pooling so that they should not effect each other.
My executer service is like this. i thought 30 threads will be enough for me.
static ExecutorService threadExecutor;
threadExecutor = Executors.newFixedThreadPool(30);
and then i submit threads in the same service.
threadExecutor.submit(monitorinternetconnectivity); //submitting swingworker obejct
Some of the threads i submit at the start and some i add runtime, when i add at runtime, it does not complete the job or stop running their job, like monitoring internet connectivity.
Is there any way to have the same functionality like swing worker, or some best way to use multiple swingworker. and we should be able to add new swingwokers at runtime to executer service
SwingWorker uses it's own ThreadPool.
SwingWorker should be used for a long running task after (i.e. anything that required more than a couple of milliseconds) after which a GUI update is required.
No calls to update gui elements outside the EDT should be done (i.e. from the SwingWorker.done() method)
If you generally follow the rules of accessing Swing components form inside the EDT (look here) then you shouldn't have a problem with locking. I suspect that the problem rather lies in your code but to be sure of that we should see it.

Dynamic change Timer service or Quartz

We need a schedule job in a Java EE server and we know how to use Quartz or the Timer service.
But our question is, if we want to change the schedule on production or manually trigger the batch, how to do it?
In the traditional solution, we use a servlet to run the job. And then use a cronjob with a http client (i.e. lynx) to trigger the servlet. It's easy to implement and could change on production.
I have never found Timers to entirely satisfactory because of this exact problem: you can't really monitor their status or modify them.
What I recommend is a second layer job manager class. When you call this class, it schedules a Java EE timer for time 'X', and it also records the fact that you want to execute a 'job' at time 'X'. When that time arrives, the Java EE timer calls this job manager class, which finds the job, and calls the job.
What this allows you to do is to write an "unschedule" function. Calling unschedule would remove the job. When the Java EE timer calls at time 'X' this class does not find any job, and so ignores it.
You can also implement a "change schedule" function that removes the old entry, and create a new entry at time 'Y' scheduling a Java EE timer for time 'Y'. The Java EE timer will arrive at both time 'X' and another at time 'Y' but only the time 'Y' will have effect.
Thus manual triggering is a matter of having a servlet that call "change schedule" to be right now.
The one other detail to be careful of: because timer events are not completely reliable, we implement this class to find all the jobs that had been scheduled before the current time, and run all of them at that moment. We then schedule extra Java EE timer events for every 5 minutes or so. Those timers will pick up any jobs that for one reason or another had been left behind. This is important if your job queue is persistent, then it might be that while restarting the server, it is down at exactly the moment that the timer was supposed to go off. No problem: Java EE Timer events themselves have no meaning, they just serve to wake up the job handler, so it can run all the outdated jobs.

How to schedule an action in java?

I'm developing an application which requires Contents of the database to be written to an ms-excel file at the end of each day. I've written the code for copying the contents into ms-excel file but Now how to proceed further? Whether threads are to be used to check for the completion of 24 hours or there's some other mechanism? Please provide me some guidance.
If you need to facility to run things at set times during the day, you should consider the Quartz Scheduler. It might be overkill, but it's very capable.
For example, you can use its CronTrigger to configure a job to run on a schedule defined by a cron expression, e.g. 0 23 55 * * ? (or something like that) would run your job at 5 to midnight every night (see examples).
Quartz recently got a boost to its future and fortunes by being acquired by the Terracotta folks. Hopefully it'll get some real active development now.
I agree with the others that using something like crontab would be better. However, if you can't do that, I would use the java.util.concurrent package added in Java 1.5. The class you would need is ScheduledThreadPoolExecutor. Specifically, the scheduleAtFixedRate() method.
I think that from the design perspective it is better to use crontab on linux platform or task scheduler on windows platform. It will keep your java program small, and simple. While the solution with thread waiting for the specific time seems simple it will add one serious concern - you will have to monitor its health.
In addition - I would suggest to carefully plan logs your job is writing each time it is run. It is important to have logs for both successful and unsuccessful runs.
It makes sense to make separate file for such logs.
One more case to be considered - what to do if database was not available exactly in the time when job run? Is it acceptable to wait another 24 hours?

Categories