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.
Related
I want schedule one java program to run at 15th,25th and 45th min of time every hour. For example:
17:15 , 17:25 , 17:45 , 18:15 and so on...
How can I acheive this using ScheduledExecutorService. I can see several examples which can trigger scripts after certain time intervals with respect to the time they are triggered using ScheduledExecutorService.
Can anyone suggest me relevent links and examples to get some idea
I could not find a way to schedule a Timer with uneven intervals. However, it is relatively straightforward to schedule a Timer to execute at fixed intervals.
For your case, you could schedule three timers, one for :15, one for :25, and one for :45 past the hour:
public class TaskTest {
public static scheduleTask(int interval) {
GregorianCalendar cal = new GregorianCalendar();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int date = cal.get(Calendar.DATE);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int hourScheduled = hour;
// if we are past the scheduled time then schedule for the next hour
if (minute > interval) {
++hourScheduled;
}
cal.set(year, month, date, hourScheduled, interval);
long initialDelay = cal.getTimeInMillis() - System.currentTimeMillis();
if (initialDelay < 0) {
initialDelay = 0L;
}
// schedule each job for once per hour
int period = 60*60*1000;
Timer timer = new Timer();
SomeTask someTask = new SomeTask();
timer.scheduleAtFixedRate(someTask, initialDelay, period);
}
public static void main(String[] args) {
// schedule for the 15th, 25th and 45th min of time every hour
scheduleTask(15);
scheduleTask(25);
scheduleTask(45);
}
}
public class SomeTask extends TimerTask {
#Override
public void run() {
// do something
}
}
You want to trigger your code at some time point, not periodically, I think there are several choices:
if your program run under Linux or other systems which support crontab, then crontab is a good choice.
We could create multi cron job to achieve your target:
use command "crontab -e" to edit cron jobs:
15 * * * * /java_path/java your_program parameters
25 * * * * /java_path/java your_program parameters
35 * * * * /java_path/java your_program parameters
45 * * * * /java_path/java your_program parameters
if you don't want to use crontab, and you just want a pure java solution, quartz will help you.
quartz could let you configure cron triggers which are little like crontab under Linux.
please refer to http://www.quartz-scheduler.org/documentation/quartz-2.2.x/tutorials/tutorial-lesson-06.html to get more information.
At last, you want a pure java, and lightweight solution, you could simply use Java Timer and TimerTask, such as:
public class App {
public static void main(String[] args) {
Timer timer = new Timer();
TimerTask tt = new SchedulerTask();
DateFormat df = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
Date triggerTime = null;
try {
triggerTime = df.parse("2016-04-12 13:15:00");
} catch (ParseException e) {
e.printStackTrace();
}
timer.schedule(tt, triggerTime, 3600*1000);
}
static class SchedulerTask extends TimerTask {
#Override
public void run() {
System.out.println("I am running at " + Calendar.getInstance().getTime());
}
}
}
you could create 4 tasks like the task above, trigger at 13:15, 13:25, 13:35, 13:45 and each task runs once for every hour.
You can schedule same runnable with fixed 1hour interval & delay should be variable based on current time.
Example current time 6:10 than delay for your first schedule will be 5min(6:15), for second schedule 5+10=15 min(6:25).
like that you can create multiple schedule each with one hour delays.
import java.util.GregorianCalendar;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class MultipleScheduler {
public static void main(String[] args) {
Runnable task = new Runnable() {
#Override
public void run() {
System.out.println(System.currentTimeMillis() + " Task executed");
}
};
ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
int BaseDelay = getInitialDelay();
service.scheduleAtFixedRate(task, BaseDelay, 60, TimeUnit.MINUTES);
service.scheduleAtFixedRate(task, BaseDelay + 10, 60, TimeUnit.MINUTES);
service.scheduleAtFixedRate(task, BaseDelay + 30, 60, TimeUnit.MINUTES);
}
static int getInitialDelay() {
GregorianCalendar cal = new GregorianCalendar();
int minute=cal.get(cal.MINUTE);
int delay=0;
//some logic to calculate delay updated delay should be returned
return delay;
}
}
I have to run a job using a thread for every 1 hour. This job is to read files in a folder. I have created a simple thread
Thread t = new Thread() {
#Override
public void run() {
while(true) {
try {
Thread.sleep(1000*60*60);
//Implementation
} catch (InterruptedException ie) {
}
}
}
};
t.start();
which runs every one hour so that I can call the function to read the files. I want to know if this approach is good or any other approach is good
You can use ScheduledExecutorService for this task, and here is a Sample Example
If you want to use just Thread then try
try {
Thread.sleep(1000 * 60 * 60);
} catch (InterruptedException ex) {}
otherwise its a good choice that you can go with ScheduledExecutorService
ScheduledExecutorService executor = ...
executor.scheduleAtFixedRate(someTask, 0, 1, TimeUnit.HOUR);
import java.util.Timer;
import java.util.TimerTask;
public class MyTimer {
public static void main(String[] args) {
OneHourJob hourJob = new OneHourJob();
Timer timer = new Timer();
timer.scheduleAtFixedRate(hourJob, 0, 5000 * 60 * 60); // this code
// runs every 5 seconds to make it one hour use this value 5000 * 60 *
// 60
}
}
class OneHourJob extends TimerTask {
#Override
public void run() {
System.out.println("Ran after one hour.");
}
}
Above code runs every five seconds. Whatever work you need to do write that code in run method of OneHourJob
With reference to Java Timer Class or ScheduledExecutorService interface ,Can I set a scheduler(or timer) inside run method (or TimerTask) of the executor thread(other scheduler)?
Case Study:
I have a database containing a list of songs(10,000) and schedule time to play the song.
So I thought of creating a scheduler(say 1)(of period 1 hour) which will search the database and create scheduler for all songs which are scheduled to be played within one hour.
After one hour the scheduler1 will delete all the threads and again search the database and create scheduler for other threads.
Is it a good idea?Possible to create?
Or should I create 10000 scheduler at once?
In this case which one will be better timer or scheduler?
Why not just call ScheduledExecutorService.scheduleAtFixedRate or ScheduledExecutorService.scheduleWithFixedDelay?
UPDATE
This is one means of implementing what (I believe) you want:
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
void start(final Connection conn)
{
executor.scheduleWithFixedDelay(new Runnable(){ public void run(){ try { poll(conn); } catch (Exception e) { e.printStackTrace(); } } }, 0, 1, TimeUnit.HOURS);
}
private void poll(Connection conn) throws SQLException
{
final ResultSet results = conn.createStatement().executeQuery("SELECT song, playtime FROM schedule WHERE playtime > GETDATE() AND playtime < GETDATE() + 1 HOUR");
while (results.next())
{
final String song = results.getString("song");
final Time time = results.getTime("playtime");
executor.schedule(new Runnable(){ public void run() { play(song); } }, time.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
}
}
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.
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.