Invoke java program at specific intervals - java

I have a program which reads Inbox messages from email accounts, as the title says i would like to run the program after every 1.5hrs.
Is there any OS(Windows and Linux) level or JVM level solution which would help in performing the task.
Thanks.

On Windows use the at command or "Scheduled Jobs", on Linux use a cron job.
http://support.microsoft.com/kb/313565
http://en.wikipedia.org/wiki/Cron

Taken from javadoc of ScheduledExecutorService:
import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() { System.out.println("beep"); }
};
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
public void run() { beeperHandle.cancel(true); }
}, 60 * 60, SECONDS);
}
}

Create a cron job.
Type crontab -e
and add an entry for your command.

Related

How to schedule a periodic task but stop and return result if a condition is fulfilled (Java)

I need to execute a certain task periodically within a certain timeout.
But dependent on the result of the task, I want to stop before the end of the timeout is reached. And in addition I need a reference to the currently executed task in order to have the chance to ask for the result.
Solution to 1) is no problem, because it can be solved with the little code snipped shown below. But I can not figure out how to integrate 2). So with this code example, I would like that the beeper object runs code which can have a positive or a negative result and based on (for example) a positive result, the beeper task should no longer be executed periodically.
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() { System.out.println("beep"); }
};
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
public void run() { beeperHandle.cancel(true); }
}, 60 * 60, SECONDS);
}
}
In your run method if condition is fulfilled then invoke scheduler.shutdown(). That should do exactly what you want.
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() {
System.out.println("beep");
if(isMyCondition() {
scheduler.shutdown();
}
}
};
See javadoc for ExecutorService.shutdown()

Is it safe to use single ScheduledExecutorService to run more than one task?

I would like to use ScheduledExecutorService to export some data in scheduled manner.
In my code below I have called 2 different task in 2 different time intervals. There will be a chance where multiple task is schedule in 1 ScheduledExecutorService when user creates multiple scheduling to export multiple data(different reports).
Is it safe to use single ScheduledExecutorService to run more than one task?
Is it possible to stop one of the task(Eg. service.scheduleAtFixedRate(runnable2, 0, 10, TimeUnit.SECONDS);) if user deletes specific scheduling?
public static void main(String... args) {
Runnable runnable = new Runnable() { public void run() {
// task to run goes here
System.out.println("Every 5 sec: "+ new java.util.Date());
}
};
Runnable runnable2 = new Runnable() {
public void run() {
// task to run goes here
System.out.println("Every 10 sec: "+ new java.util.Date());
}
};
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(runnable, 0, 5, TimeUnit.SECONDS);
service.scheduleAtFixedRate(runnable2, 0, 10, TimeUnit.SECONDS);
}

Run java program in every 15 minutes

Following is a sample code from my program which queries the database and results are copied to different files in a directory. What I want to achieve is following code should run in 15 minutes interval so that Files are updated with the new data.
public class CountryLogtoCSV {
static Connection con = null;
static ResultSet rs = null;
public static void main(String... argv)
{
FileWriter filewriter=null;
File countryHits=new File("countryhits.csv");
filewriter=new FileWriter(countryHits);
query = "SELECT countryID, count(*) as total FROM mobileCountryLog"
+ " WHERE aHitType='ALL' AND aDate>'2012-11-06' GROUP BY countryID";
rs = Database.getResult(connection,query)
while (rs.next()) {
//Writing result to File, FileWriter is used
filewriter.append(rs.getString("countryID"));
filewriter.append(rs.getString("total"));
filewriter.flush();
}
File countryUnique=new File("countryunique.csv");
filewriter=new FileWriter(countryUnique);
query = "SELECT countryID, count(*) as total FROM mobileCountryLog"
+ " WHERE (aHitType='UNIQUE'AND aDate>'2012-11-06' GROUP BY countryID;
rs = Database.getResult(connection,query)
while (rs.next()) {
//Writing Result to File, FileWriter is used
filewriter.append(rs.getString("countryID"));
filewriter.append(rs.getString("total"));
filewriter.flush();
}
rs.close();
}
}
How to run this java class in every 15 minutes??
Thanks,
If you are running on Unix type OS, then you can do this with cron:
Add this to the crontab:
*/15 * * * * /yourpath-to-jdk/bin/java -cp yourclasspath CountryLogtoCSV
You can also do it in Java using the Executor package, but that means you will have to have that code running at all time or else it won't execute. With cron, your code only needs to run every 15 minutes (or whatever you set the time to be). This means that if your server reboots or your code crashes at one time, it will try again at the next cycle. Much more stable and easier to manage.
You can use the ScheduledExecutorService for this
Here is an example:-
import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() { System.out.println("beep"); }
};
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
public void run() { beeperHandle.cancel(true); }
}, 60 * 60, SECONDS);
}
}
In you case you need to bundle up your code something like this.
import static java.util.concurrent.TimeUnit.*;
public class CountryLogtoCSV{
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void logtoCSV() {
final Runnable logger= new Runnable() {
//You application logic as shown in the question
};
final ScheduledFuture<?> loggerHandle =
scheduler.scheduleAtFixedRate(logger, 15, 15, MINUTES );
//Incase you want to kill this after some time like 24 hours
scheduler.schedule(new Runnable() {
public void run() { loggerHandle.cancel(true); }
}, 24, HOURS );
}
}
Hope this helps
Better you can go with quartz scheduler to execute your code periodically. try with the below reference
http://www.mkyong.com/java/quartz-scheduler-example/
If you do not want to use the schedulers and do not want to change the time limits, most basic solution is to use a simple thread, and sleep for (15*90*1000) miliseconds... Helpful and effective if you do not want to use 3rd party s/w.

How can i make a Java Daemon

I need to do a periodic operation (call a java method) in my web app (jsp on tomcat).
How can i do this ? Java daemon or others solutions ?
You could use a ScheduledExecutorService for periodic execution of a task. However, if you require more complex cron-like scheduling then take a look at Quartz. In particular I'd recommend using Quartz in conjunction with Spring if you go down this route, as it provides a nicer API and allows you to control your job firing in configuration.
ScheduledExecutorService Example (taken from Javadoc)
import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() { System.out.println("beep"); }
};
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
public void run() { beeperHandle.cancel(true); }
}, 60 * 60, SECONDS);
}
}
Adams answer is right on the money. If you do end up rolling your own (rather than going the quartz route), you'll want to kick things off in a ServletContextListener. Here's an example, using java.util.Timer, which is more or less a dumb version of the ScheduledExexutorPool.
public class TimerTaskServletContextListener implements ServletContextListener
{
private Timer timer;
public void contextDestroyed( ServletContextEvent sce )
{
if (timer != null) {
timer.cancel();
}
}
public void contextInitialized( ServletContextEvent sce )
{
Timer timer = new Timer();
TimerTask myTask = new TimerTask() {
#Override
public void run()
{
System.out.println("I'm doing awesome stuff right now.");
}
};
long delay = 0;
long period = 10 * 1000; // 10 seconds;
timer.schedule( myTask, delay, period );
}
}
And then this goes in your web.xml
<listener>
<listener-class>com.TimerTaskServletContextListener</listener-class>
</listener>
Just more food for thought!

How to run a method at XX:XX:XX time?

HI
I want to run a method in my program evry X hours, how to do that ?
Im googling and there is nothing :/
You could consider Quartz.
It is some sort of cron that runs inside java. I admit though that it is probably an overkill if you want to schedule only one job.
You could take a look at the Timer class, but the best option is to use a ScheduledExecutorService:
e.g. This will beep at a scheduled rate:
import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() {
System.out.println("beep");
}
};
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
public void run() {
beeperHandle.cancel(true);
}
}, 60 * 60, SECONDS);
}
}
I use the Quartz framework for most of my scheduling ( http://www.quartz-scheduler.org/ ) but if you're doing something simple, java.util.Timer is fine.
// in a class body...
public static void main( String[] argv ) {
Timer timer = new Timer();
int secondsBetweenRuns = 3600;
timer.schedule( new MyOwnTask(), 0, secondsBetweenRuns * 1000 );
}
static class MyOwnTask extends TimerTask {
public void run() {
doWhateverYouNeedToDoEveryHour();
}
}
Scheduled Task (in Windows) or Cron (in Unix)
You could save the time at a certain point, than start a timer. When the time is up, you run the method and restart the timer.

Categories