How to make Java code that opens the program hourly - java

I'm trying to make code that opens hourly programs made in Java. I have little knowledge of java. I tried to do similar below but it doesn't work as I want.
Code:
public static void main(String[] args) throws Exception {
for(int i = 0; i < 5; i++) {
Runtime runtime = Runtime.getRuntime();
String[] s = new String[] {"C:\\Program Files\\BraveSoftware\\Brave-Browser\\Application\\brave.exe"};
Process process = runtime.exec(s);
}
}

If you are looking for running this program in a scheduled manner, you can use something like
Task Scheduler in windows or Crontab in case of UNIX systems.
You need not install and run Java for that. But, if you really need it to be executed using a java code, then you can use inbuilt scheduling options in Java. One of the approach is to use a TimerTask . Added an example below
public class Task extends TimerTask {
#Override
public void run() {
try {
// I don't know, what is this app, basically you execute the logic here
Runtime runtime = Runtime.getRuntime();
String[] s = new String[] { "C:\\Program Files\\BraveSoftware\\Brave-Browser\\Application\\brave.exe" };
Process process = runtime.exec(s);
} catch (IOException e) {
// Do your thing with the errors!
e.printStackTrace();
}
}
}
And your scheduler goes like this.
public class Scheduler {
public static void main(String[] args) {
//Create a timer for scheduling
Timer schduleManager = new Timer();
//Create your task instance
Task taskInstance = new Task();
//Scheduler your task repeatedly - every one hour
schduleManager.schedule(taskInstance, 0, TimeUnit.HOURS.toMillis(1));
System.out.println(TimeUnit.HOURS.toMillis(1));
// Keep your code running - an eg.
while(true);
}
}
The program has to be exited forcefully with a Cntrl+C or console kill. There are other similar options , using different libraries as well, like
java.util.concurrent.ScheduledExecutorService
Quartz Scheduler
And more. You can explore on this.

If you are using spring boot then you can use Scheduler annotation
#Scheduled(fixedDelay = 60 * 60 * 1000

This seems to be a job requiring Java's ScheduledExecutorService. According to Java's documentation
The ScheduledExecutorService interface supplements the methods of its
parent ExecutorService with schedule, which executes a Runnable or
Callable task after a specified delay. In addition, the interface
defines scheduleAtFixedRate and scheduleWithFixedDelay, which executes
specified tasks repeatedly, at defined intervals.
Here's an example from its Javadoc that sets up a ScheduledExecutorService to beep every ten seconds for an hour:
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);
}
}
Here is a link to a StackOverflow answer that uses ScheduledExecutorService to run a task at a specific time.
Another alternative is to run your task as a CRON job. Here's a link to a StackOverflow answer that uses CRON to schedule a Java program.

If I understood your question correctly you can use Thread.sleep() to idle and then start the Process.
So I guess something like this would work:
public static void main(String[] args) throws InterruptedException, IOException {
ProcessBuilder pb = new ProcessBuilder("path\\to\\file.exe");
while (true) {
pb.start();
Thread.sleep(Duration.ofHours(1).toMillis());
}
}

Related

How can I use java scheduledExecutor service to run a java code at a specific time of a day?

I need to run a specific java program at a particular time of the day and I need to modify the following code to make it run at a particular time of the day.
private final static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public static void main(String args[]) {
final Runnable beeper = new Runnable() {
public void run() {
System.out.println("beep");
}
};
final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(beeper, 0, 1, SECONDS);
scheduler.schedule(new Runnable() {
public void run() {
beeperHandle.cancel(true);
}
}, 60 * 60, SECONDS);
}
You have to use ScheduledExecutorService ? It's not good for scheduling tasks at specific time. It's ment to be used for delayed/repeated actions. Have you seen Quartz ? Documentation has nice examples and library allows you to be very specific about time of task.
quartz doc ex1
quartz doc ex2
//edit:
Here you have example implementation example: https://www.mkyong.com/java/quartz-2-scheduler-tutorial/
You can use: https://hc.apache.org/httpcomponents-client-ga/examples.html
It allows to do simple calls. Like this:
HttpGet httpGet = new HttpGet("http://somesite.com");
BasicHttpClientConnectionManager manager = new BasicHttpClientConnectionManager();
HttpClient client = new MinimalHttpClient(manager);
client.execute(httpGet);
Put this code into job and it should work.
You can check actual time in beeper each time it is invoked and beep only at requested hosr:
public void run() {
if (Calendar.getInstance().get(Calendar.HOUR_OF_DAY) == REQUESTED_HOUR) {
System.out.println("beep");
}

Java 8 Spring Update REST every 5min [duplicate]

I need to schedule a task to run in at fixed interval of time. How can I do this with support of long intervals (for example on each 8 hours)?
I'm currently using java.util.Timer.scheduleAtFixedRate. Does java.util.Timer.scheduleAtFixedRate support long time intervals?
Use a ScheduledExecutorService:
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(yourRunnable, 8, 8, TimeUnit.HOURS);
You should take a look to Quartz it's a java framework wich works with EE and SE editions and allows to define jobs to execute an specific time
Try this way ->
Firstly create a class TimeTask that runs your task, it looks like:
public class CustomTask extends TimerTask {
public CustomTask(){
//Constructor
}
public void run() {
try {
// Your task process
} catch (Exception ex) {
System.out.println("error running thread " + ex.getMessage());
}
}
}
Then in main class you instantiate the task and run it periodically started by a precised date:
public void runTask() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendar.set(Calendar.HOUR_OF_DAY, 15);
calendar.set(Calendar.MINUTE, 40);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Timer time = new Timer(); // Instantiate Timer Object
// Start running the task on Monday at 15:40:00, period is set to 8 hours
// if you want to run the task immediately, set the 2nd parameter to 0
time.schedule(new CustomTask(), calendar.getTime(), TimeUnit.HOURS.toMillis(8));
}
Use Google Guava AbstractScheduledService as given below:
public class ScheduledExecutor extends AbstractScheduledService {
#Override
protected void runOneIteration() throws Exception {
System.out.println("Executing....");
}
#Override
protected Scheduler scheduler() {
return Scheduler.newFixedRateSchedule(0, 3, TimeUnit.SECONDS);
}
#Override
protected void startUp() {
System.out.println("StartUp Activity....");
}
#Override
protected void shutDown() {
System.out.println("Shutdown Activity...");
}
public static void main(String[] args) throws InterruptedException {
ScheduledExecutor se = new ScheduledExecutor();
se.startAsync();
Thread.sleep(15000);
se.stopAsync();
}
}
If you have more services like this, then registering all services in ServiceManager will be good as all services can be started and stopped together. Read here for more on ServiceManager.
If you want to stick with java.util.Timer, you can use it to schedule at large time intervals. You simply pass in the period you are shooting for. Check the documentation here.
Do something every one second
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
//code
}
}, 0, 1000);
These two classes can work together to schedule a periodic task:
Scheduled Task
import java.util.TimerTask;
import java.util.Date;
// Create a class extending TimerTask
public class ScheduledTask extends TimerTask {
Date now;
public void run() {
// Write code here that you want to execute periodically.
now = new Date(); // initialize date
System.out.println("Time is :" + now); // Display current time
}
}
Run Scheduled Task
import java.util.Timer;
public class SchedulerMain {
public static void main(String args[]) throws InterruptedException {
Timer time = new Timer(); // Instantiate Timer Object
ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask class
time.schedule(st, 0, 1000); // Create task repeating every 1 sec
//for demo only.
for (int i = 0; i <= 5; i++) {
System.out.println("Execution in Main Thread...." + i);
Thread.sleep(2000);
if (i == 5) {
System.out.println("Application Terminates");
System.exit(0);
}
}
}
}
Reference https://www.mkyong.com/java/how-to-run-a-task-periodically-in-java/
If your application is already using Spring framework, you have Scheduling built in
I use Spring Framework's feature. (spring-context jar or maven dependency).
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
#Component
public class ScheduledTaskRunner {
#Autowired
#Qualifier("TempFilesCleanerExecution")
private ScheduledTask tempDataCleanerExecution;
#Scheduled(fixedDelay = TempFilesCleanerExecution.INTERVAL_TO_RUN_TMP_CLEAN_MS /* 1000 */)
public void performCleanTempData() {
tempDataCleanerExecution.execute();
}
}
ScheduledTask is my own interface with my custom method execute, which I call as my scheduled task.
You can also use JobRunr, an easy to use and open-source Java Scheduler.
To schedule a Job every 8 hours using JobRunr, you would use the following code:
BackgroundJob.scheduleRecurrently(Duration.ofHours(8), () -> yourService.methodToRunEvery8Hours());
If you are using Spring Boot, Micronaut or Quarkus, you can also use the #Recurring annotation:
public class YourService {
#Recurring(interval="PT8H")
public void methodToRunEvery8Hours() {
// your business logic
}
}
JobRunr also comes with an embedded dashboard that allows you to follow-up on how your jobs are doing.
Have you tried Spring Scheduler using annotations ?
#Scheduled(cron = "0 0 0/8 ? * * *")
public void scheduledMethodNoReturnValue(){
//body can be another method call which returns some value.
}
you can do this with xml as well.
<task:scheduled-tasks>
<task:scheduled ref = "reference" method = "methodName" cron = "<cron expression here> -or- ${<cron expression from property files>}"
<task:scheduled-tasks>
my servlet contains this as a code how to keep this in scheduler if a user presses accept
if(bt.equals("accept")) {
ScheduledExecutorService scheduler=Executors.newScheduledThreadPool(1);
String lat=request.getParameter("latlocation");
String lng=request.getParameter("lnglocation");
requestingclass.updatelocation(lat,lng);
}
There is a ScheduledFuture class in java.util.concurrent, it may helps you.

How to schedule a periodic task in Java?

I need to schedule a task to run in at fixed interval of time. How can I do this with support of long intervals (for example on each 8 hours)?
I'm currently using java.util.Timer.scheduleAtFixedRate. Does java.util.Timer.scheduleAtFixedRate support long time intervals?
Use a ScheduledExecutorService:
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(yourRunnable, 8, 8, TimeUnit.HOURS);
You should take a look to Quartz it's a java framework wich works with EE and SE editions and allows to define jobs to execute an specific time
Try this way ->
Firstly create a class TimeTask that runs your task, it looks like:
public class CustomTask extends TimerTask {
public CustomTask(){
//Constructor
}
public void run() {
try {
// Your task process
} catch (Exception ex) {
System.out.println("error running thread " + ex.getMessage());
}
}
}
Then in main class you instantiate the task and run it periodically started by a precised date:
public void runTask() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendar.set(Calendar.HOUR_OF_DAY, 15);
calendar.set(Calendar.MINUTE, 40);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Timer time = new Timer(); // Instantiate Timer Object
// Start running the task on Monday at 15:40:00, period is set to 8 hours
// if you want to run the task immediately, set the 2nd parameter to 0
time.schedule(new CustomTask(), calendar.getTime(), TimeUnit.HOURS.toMillis(8));
}
Use Google Guava AbstractScheduledService as given below:
public class ScheduledExecutor extends AbstractScheduledService {
#Override
protected void runOneIteration() throws Exception {
System.out.println("Executing....");
}
#Override
protected Scheduler scheduler() {
return Scheduler.newFixedRateSchedule(0, 3, TimeUnit.SECONDS);
}
#Override
protected void startUp() {
System.out.println("StartUp Activity....");
}
#Override
protected void shutDown() {
System.out.println("Shutdown Activity...");
}
public static void main(String[] args) throws InterruptedException {
ScheduledExecutor se = new ScheduledExecutor();
se.startAsync();
Thread.sleep(15000);
se.stopAsync();
}
}
If you have more services like this, then registering all services in ServiceManager will be good as all services can be started and stopped together. Read here for more on ServiceManager.
If you want to stick with java.util.Timer, you can use it to schedule at large time intervals. You simply pass in the period you are shooting for. Check the documentation here.
Do something every one second
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
//code
}
}, 0, 1000);
These two classes can work together to schedule a periodic task:
Scheduled Task
import java.util.TimerTask;
import java.util.Date;
// Create a class extending TimerTask
public class ScheduledTask extends TimerTask {
Date now;
public void run() {
// Write code here that you want to execute periodically.
now = new Date(); // initialize date
System.out.println("Time is :" + now); // Display current time
}
}
Run Scheduled Task
import java.util.Timer;
public class SchedulerMain {
public static void main(String args[]) throws InterruptedException {
Timer time = new Timer(); // Instantiate Timer Object
ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask class
time.schedule(st, 0, 1000); // Create task repeating every 1 sec
//for demo only.
for (int i = 0; i <= 5; i++) {
System.out.println("Execution in Main Thread...." + i);
Thread.sleep(2000);
if (i == 5) {
System.out.println("Application Terminates");
System.exit(0);
}
}
}
}
Reference https://www.mkyong.com/java/how-to-run-a-task-periodically-in-java/
If your application is already using Spring framework, you have Scheduling built in
I use Spring Framework's feature. (spring-context jar or maven dependency).
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
#Component
public class ScheduledTaskRunner {
#Autowired
#Qualifier("TempFilesCleanerExecution")
private ScheduledTask tempDataCleanerExecution;
#Scheduled(fixedDelay = TempFilesCleanerExecution.INTERVAL_TO_RUN_TMP_CLEAN_MS /* 1000 */)
public void performCleanTempData() {
tempDataCleanerExecution.execute();
}
}
ScheduledTask is my own interface with my custom method execute, which I call as my scheduled task.
You can also use JobRunr, an easy to use and open-source Java Scheduler.
To schedule a Job every 8 hours using JobRunr, you would use the following code:
BackgroundJob.scheduleRecurrently(Duration.ofHours(8), () -> yourService.methodToRunEvery8Hours());
If you are using Spring Boot, Micronaut or Quarkus, you can also use the #Recurring annotation:
public class YourService {
#Recurring(interval="PT8H")
public void methodToRunEvery8Hours() {
// your business logic
}
}
JobRunr also comes with an embedded dashboard that allows you to follow-up on how your jobs are doing.
Have you tried Spring Scheduler using annotations ?
#Scheduled(cron = "0 0 0/8 ? * * *")
public void scheduledMethodNoReturnValue(){
//body can be another method call which returns some value.
}
you can do this with xml as well.
<task:scheduled-tasks>
<task:scheduled ref = "reference" method = "methodName" cron = "<cron expression here> -or- ${<cron expression from property files>}"
<task:scheduled-tasks>
my servlet contains this as a code how to keep this in scheduler if a user presses accept
if(bt.equals("accept")) {
ScheduledExecutorService scheduler=Executors.newScheduledThreadPool(1);
String lat=request.getParameter("latlocation");
String lng=request.getParameter("lnglocation");
requestingclass.updatelocation(lat,lng);
}
There is a ScheduledFuture class in java.util.concurrent, it may helps you.

How to set a timer but don't run repeatly

In my case I created a object and planned to release it after 20 minutes(accuracy is not necessary). I know by using java.util.Timer I can create a timer.But I just want it run once. After that,the timer should stop and been released too.
Is there any way just like setTimeOut() in javascript?
Thanks.
int numberOfMillisecondsInTheFuture = 10000; // 10 sec
Date timeToRun = new Date(System.currentTimeMillis()+numberOfMillisecondsInTheFuture);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
// Task here ...
}
}, timeToRun);
Modify above so that you can schedule a job 20 minutes in future.
Use Timer::schedule(TimerTask, long) or look into the ScheduledThreadPoolExecutor or ScheduledExecutorService classes.
You can start a new thread and call sleep with the number of milliseconds to wait, then execute your instructions (on either thread). See http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html for reference, and look at the various online thread tutorials if you need more help.
java.util.Timer has a cancel method in it:
http://download.oracle.com/javase/6/docs/api/java/util/Timer.html#cancel%28%29
However, as far as I know, in timer if you do not specify a period, scheduled task will run only once.
package com.stevej;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class StackOverflowMain {
public static void main(String[] args) {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
Runnable myAction = new Runnable() {
#Override
public void run() {
System.out.println("Hello (2 minutes into the future)");
}
};
executor.schedule(myAction, 2, TimeUnit.MINUTES);
}
}

ScheduledThreadPoolExecutor scheduleWithFixedDelay and "urgent" execution

I have the following problem that the standard library doesn't solve well, and I'm wondering if anybody has seen another library out there than can do it so I don't need to hack together a custom solution. I have a task that is currently scheduled on a thread pool using scheduleWithFixedDelay(), and I need to modify the code to handle requests for "urgent" execution of the task related to asynchronous events. Thus, if the task is scheduled to occur with a delay of 5 minutes between executions, and an event occurs 2 minutes after the last completed execution, I would like to execute the task immediately and then have it wait for 5 minutes after the completion of the urgent execution before it runs again. Right now the best solution that I can come up with is to have the event handler call cancel() on the ScheduledFuture object returned by scheduleWithFixedDelay() and execute the task immediately, and then set a flag in the task to tell it to reschedule itself with the same delay parameters. Is this functionality available already and I'm just missing something in the documentation?
If you are using ScheduledThreadPoolExecutor there is a method decorateTask (well in fact there are two, for Runnable and Callable tasks) that you can override to store a reference to the task somewhere.
When you need urgent execution, you just call run() on that reference which makes it run and rescheduled with same delay.
A quick hack-up attempt:
public class UrgentScheduledThreadPoolExecutor extends
ScheduledThreadPoolExecutor {
RunnableScheduledFuture scheduledTask;
public UrgentScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize);
}
#Override
protected RunnableScheduledFuture decorateTask(Runnable runnable,
RunnableScheduledFuture task) {
scheduledTask = task;
return super.decorateTask(runnable, task);
}
public void runUrgently() {
this.scheduledTask.run();
}
}
which can be used like this:
public class UrgentExecutionTest {
public static void main(String[] args) throws Exception {
UrgentScheduledThreadPoolExecutor pool = new UrgentScheduledThreadPoolExecutor(5);
pool.scheduleWithFixedDelay(new Runnable() {
SimpleDateFormat format = new SimpleDateFormat("ss");
#Override
public void run() {
System.out.println(format.format(new Date()));
}
}, 0, 2L, TimeUnit.SECONDS);
Thread.sleep(7000);
pool.runUrgently();
pool.awaitTermination(600, TimeUnit.SECONDS);
}
}
and produces the following output:
06
08
10
11
13
15
as requested (soz, in a hurry) my EventBasedExecutor
Warning: This currently only works for tasks that are scheduled in a periodic run. You can change the code to handle all the tasks, I so far haven't because I only have the periodically run task. I also run this in a signle-threaded threadpool (I only need one scheduled runner thread that is that runs in one dedicated thread all the time every X seconds)
Here we go:
public class EventBasedExecutor extends ScheduledThreadPoolExecutor implements EventBasedExecutorService {
private List<RunnableScheduledFuture<?>> workers = new ArrayList<>();
private int index;
public EventBasedExecutor(int corePoolSize) {
super(corePoolSize, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("message-sender-%d").build());
}
#Override
protected <V> RunnableScheduledFuture<V> decorateTask(Runnable runnable, RunnableScheduledFuture<V> task) {
if(!workers.contains(runnable)) {
workers.add(task);
}
return super.decorateTask(runnable, task);
}
#Override
public void executeEarly() {
if(index >= workers.size()) {
index = 0;
}
if(workers.size() == 0) {
return;
}
RunnableScheduledFuture<?> runnableScheduledFuture = workers.get(index);
index ++;
execute(runnableScheduledFuture);
System.out.println("Executing");
}
public static void main(String[] args) throws InterruptedException {
EventBasedExecutor executor = new EventBasedExecutor(10);
long currentTimeMillis = System.currentTimeMillis();
// this will never run
executor.scheduleAtFixedRate(() -> {
System.out.println("hello");
}, 5000, 5000, TimeUnit.HOURS);
executor.executeEarly();
System.out.println("Run after: " + (System.currentTimeMillis() - currentTimeMillis));
}
}
This will execute the task in the dedicated worker thread.
It will print:
Executing
hello
Run after: 39
Have fun hacking :)
artur
There is also an obvious simple solution that does not require a new class.
The idea is to cancel the schedule on notification and re-schedule again:
class MyClass {
final static int DECISION_POINT = 1; //millisecond
final ScheduledExecutorService executor = newSingleThreadScheduledExecutor();
private ScheduledFuture<?> periodicFuture;
MyClass() {
periodicFuture = executor.scheduleWithFixedDelay(this::doWork, 1, 2,
TimeUnit.SECONDS);
}
void doWorkAsap() {
if (periodicFuture.getDelay(TimeUnit.MILLISECONDS) > DECISION_POINT) {
periodicFuture.cancel(true);
periodicFuture = executor.scheduleWithFixedDelay(this::doWork,
0, 2000, TimeUnit.MILLISECONDS);
}
}
void doWork() { ... }
}
This only works well in certain situations where delay between tasks is reasonably big relative to overall system performance and overhead of creating new ScheduledFuture is acceptable. Also, special attention needs to be paid to the point of no return, called DECISION_POINT here, where it makes no more sense to schedule the new future, as natural order of things would be fast enough. For the tighter schedules than in the example above, use an approach similar to the pandaab one.

Categories