How to create number of timer.scheduler inside the run method - java

I want to create 10 Timer.scheduler inside the run method, so i used for loop but its executing only once. not repeatedly calling the scheduler in this loop.
Please check my code below,
public void run()
{
for(int i=0;i<10;i++)
{
timer.schedule(task, 10000);
}
}
In this code I created 10 schedulers using for for loop but it executing only once. And how to differentiate each Scheduler
Please help me,

Assuming you're using java.util.Timer then possibly the reason why it's only running the task once is because a java.util.TimerTask can only be scheduled once. This code will run the first scheduled task but will fail with an java.lang.IllegalStateException: Task already scheduled or cancelled there after.
To differentiate each scheduled task you could do something like this. Each scheduled NamedTimerTask will have its own name. You can choose to modify this to add whatever you need to identify your scheduled tasks.
public static void main(String[] args) {
Timer timer = new Timer();
for (int i = 0; i < 10; i++) {
timer.schedule(new NamedTimerTask("task" + i) {
#Override
public void run() {
System.out.println(name);
}
}, 1000);
}
}
static abstract class NamedTimerTask extends TimerTask {
final String name;
NamedTimerTask(String name) {
this.name = name;
}
}

Related

Java while function only evey 1 second

I have a while function. When it is true I want to proceed it only every 1 second. I can't use Thread.sleep(), because I am making Minecraft plugin and it will stop all processes on the server. Is there another way how to do it?
Thanks for your reply.
What you are looking for is the Bukkit Scheduler. It is integrated into the default plugin API and can be used to solve your task as following:
int taskID = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
#Override
public void run() {
// do stuff
}
}, delay, repeat);
Set the delay to 0 and the repeat to 20 (20 Ticks are 1 second).
Stop it by using:
Bukkit.getScheduler().cancelTask(taskID);
you can create a java.util.TimerTask
which can schedule your task after a specified time delay .
more details here : https://www.geeksforgeeks.org/java-util-timertask-class-java/
If you use Thread.sleep() in the main Thread you will block the main thread and for avoid this you need to create a separate thread pass to then the values you will need for process whatever you want in your thread, some snippet code for clarification:
public static boolean ENABLE_THREAD = true;
public static void main(String args[]){
InnerThread minecraftThread = (new ThreadStack()).new InnerThread();
minecraftThread.run();
}
public class InnerThread implements Runnable{
#Override
public void run() {
int counter=0;
while(ENABLE_THREAD){
try {
//YOUR CODE
System.out.println(counter);
Thread.sleep(1000);
counter++;
if(counter>10){
ENABLE_THREAD = false;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
You can use System.currentTimeMillis():
public static void main(String[] args) {
//The while(true) is to keep the next while loop running, otherwise, in
//this example, the condition System.currentTimeMillis()-past>=1000
//won't be true
//It can be changed according to the needs
long past = System.currentTimeMillis();
while(true)
while(System.currentTimeMillis()-past>=1000)
{
/*
*DO what you need to do
*/
past = System.currentTimeMillis();
}
}
This is the simplest solution I can think of. Please check if it works for you.
long start = new Date().getTime();
while(new Date().getTime() - start < 1000L)
{
//Do Something every 1sec
//you need to update the start value everytime
start = new Date().getTime();
}

Java terminate a timertask using data from the task itself

I have got the basics of how Timer and TimerTask work in Java. I have a situation where I need to spawn a task that will run periodically at fixed intervals to retrieve some data from database. And it needs to be terminated based on the value of the retrieved data (the data itself is being updated by other processes)
Here is what I came up with so far.
public class MyTimerTask extends TimerTask {
private int count = 0;
#Override
public void run() {
count++;
System.out.println(" Print a line" + new java.util.Date() + count);
}
public int getCount() {
return count;
}
}
And a class with a main method like so. For now I have trivially used a 15 second sleep to control how long the timerTask runs.
public class ClassWithMain {
public static void main(String[] args) {
System.out.println("Main started at " + new java.util.Date());
MyTimerTask timerTask = new MyTimerTask();
Timer timer = new Timer(true);
timer.scheduleAtFixedRate(timerTask, 0, 5*10*100);
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Main done"+ new java.util.Date());
}
The MyTimerTask class will become more complex with the database service calls and so on.
What I want to be able to do is, in the main class, interrogate a value returned by timerTask to dictate when to invoke timer.cancel() and terminate the process. Right now if I try to use the count property of MyTimerTask it doesn't work. So when I tried adding these lines in ClassWithMain
if (timerTask.getCount() == 5){
timer.cancel();
}
it didn't stop the process.
So I'd like any direction on how I might be able to accomplish what I'm trying to do.
private volatile int count = 0; It is better to use 'volatile'.
try this in ClassWithMain:
for(;;) {
if (timerTask.getCount() == 5) {
timer.cancel();
break;
} else{
Thread.yield();
}
}

How to call method in every minute using Java but in background without affect current process?

When program will be started then automatically call one method in every minute in background without using thread.
class Abc
{
main()
{
do something......
}
}
class xyz
{
public void show()
{
call every 1 minute in background
do something.....
with out affect main method
}
}
You can't do 2 things at one time with only 1 thread. You have to create another thread.
Assuming that you need to call show() every 1 min from main without interfering main() code
class Abc
{
main()
{
Thread mythread = new Thread()
{
xyz myClass = new xyz();
public void run()
{
while(true)
{
myClass.show() // this will execute
thread.sleep(60000); // this will pause for a bit but wont affect your main code, add this in between try and catch to pause this thread alone withotu affecting main one for 1 min and it goes again and calls show()
}
}
}
do something......
}
}
class xyz
{
public void show()
{
// whatever you type here will now run every 1 min, without affecting your main code
}
}
You can use ScheduledExecutorService for this task.
public static class Scheduler {
private Runnable task;
private ScheduledExecutorService executorService;
public Scheduler(Runnable task, ScheduledExecutorService executorService) {
this.task = task;
this.executorService = executorService;
}
public void start(long startDelay, long period ) {
executorService.scheduleAtFixedRate(task, startDelay, period, TimeUnit.MINUTES);
}
}

Is there a code to check if a timer is running?

I have a game where I am scheduling a timer. I have this CoresManager file:
package com.rs.cores;
import java.util.Timer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
public final class CoresManager {
protected static volatile boolean shutdown;
public static WorldThread worldThread;
public static ExecutorService serverWorkerChannelExecutor;
public static ExecutorService serverBossChannelExecutor;
public static Timer fastExecutor;
public static ScheduledExecutorService slowExecutor;
public static int serverWorkersCount;
public static void init() {
worldThread = new WorldThread();
int availableProcessors = Runtime.getRuntime().availableProcessors();
serverWorkersCount = availableProcessors >= 6 ? availableProcessors - (availableProcessors >= 12 ? 7 : 5) : 1;
serverWorkerChannelExecutor = availableProcessors >= 6 ? Executors
.newFixedThreadPool(availableProcessors - (availableProcessors >= 12 ? 7 : 5),
new DecoderThreadFactory()) : Executors.newSingleThreadExecutor(new DecoderThreadFactory());
serverBossChannelExecutor = Executors
.newSingleThreadExecutor(new DecoderThreadFactory());
fastExecutor = new Timer("Fast Executor");
slowExecutor = availableProcessors >= 6 ? Executors.newScheduledThreadPool(availableProcessors >= 12 ? 4 : 2,
new SlowThreadFactory()) : Executors
.newSingleThreadScheduledExecutor(new SlowThreadFactory());
worldThread.start();
}
public static void shutdown() {
serverWorkerChannelExecutor.shutdown();
serverBossChannelExecutor.shutdown();
fastExecutor.cancel();
slowExecutor.shutdown();
shutdown = true;
}
private CoresManager() {
}
}
I am using this inside the game:
private void startTimer() {
CoresManager.fastExecutor.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (timer == 0 || timer < 1) {
player.sm("Your timer has ended! The NPCs will no longer spawn.");
timer = 0;
this.cancel();
exitInstance();
return;
}
timer--;
timerchecker = true;
seconds = timer % 60;
player.setTimer(timer);
minutes = TimeUnit.SECONDS.toMinutes(timer);
}
}, 0, 1000);
}
The CoresManager Timer stops running if the player logs out AND the server gets rebooted. To make it run again, I added a code to make it do startTimer() again once you log back in. However, since the timer still runs if the server didn't log out, the timer starts running twice. The Timer starts getting subtracted by 2, or more, depending on how many times you log out and in. I figure that it would fix if there was a code to determine if the timer is already running. Is there a way to do this? Please help!
I don't see anything in the documentation that provides for checking the status on a TimerTask object (http://docs.oracle.com/javase/1.5.0/docs/api/java/util/TimerTask.html) so one option would be to extend TimerTask and create your own class. Instead of using an anonymous TimerTask, you could create something along the lines of:
public class CoresTimerTask extends TimerTask {
private boolean hasStarted = false;
#Overrides
public void run() {
this.hasStarted = true;
//rest of run logic here...
}
public boolean hasRunStarted() {
return this.hasStarted;
}
}
and just maintain a reference to this CoresTimerTask object, which you then pass into startTimer(). You can then later check this object via hasRunStarted.
public long scheduledExecutionTime()
Returns the scheduled execution time of the most recent actual execution of this task. (If this method is invoked while task execution is in progress, the return value is the scheduled execution time of the ongoing task The return value is undefined if the task has yet to commence its first execution.
This method is typically not used in conjunction with fixed-delay execution repeating tasks, as their scheduled execution times are allowed to drift over time, and so are not terribly significant.
first thing periodically running tasks need set/reset state flag
second (when i look at examples) it is better to seal this type of class
but if someone insist to have such methods
public abstract class NonInterruptableTask extends TimerTask {
protected boolean isDone = false;
public boolean isDone() {return isDone;}
protected abstract void doTaskWork();
#Override
public void run() {
isDone = false;
doTaskWork();
isDone = true;
}
}
usage:
TimerTask myTask = new NonInterruptableTask() {
#Override
public void doTaskWork() {
//job here
}
};
you could also declare a boolean state called like "timerstate" or whatever and make it by default to be false. whenever you start a timer you could change this boolean to true and you'd be able to keep track of the timer.
public boolean timerstate;
public Timer t1;
// some code goes here to do whatever you want
if(timerstate == true) {
t1.cancel();
t1.purge();
t1 = new Timer();
} else{
t1.schedule(new TimerTask() {
#Override
public void run() {
timerstate = true;
//rest of code for the timer goes here
}
}
}

how to execute certain tasks in intervals(task schedular)

I have some type of task for example in a loop with same method but different arguments,
I need to execute these tasks in one after another in some intervals,
and all this activity need to be execute in again and again in a particular schedule,
e.g. let say I have a method called
public void GetData(String tablename){
}
so first time I will provide table1 then table2 then table3.....
similar to for loop but need some interval in between,
and same above all execution need to execute in each 10 min,
sample code I have implemented as
final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
final Runnable runner = new Runnable() {
public void run() {
getData(String table);
}
};
final ScheduledFuture<?> taskHandle =
scheduler.scheduleAtFixedRate(runner, 1, 10, SECONDS);
its working fine for one table for need help and best way to implement for multiple tables.
tryjava.util.Timer to schedule a task to execute
public class ReminderBeep {
Toolkit toolkit;
Timer timer;
public ReminderBeep(int seconds) {
toolkit = Toolkit.getDefaultToolkit();
timer = new Timer();
timer.schedule(new RemindTask(), seconds * 1000);
}
class RemindTask extends TimerTask {
public void run() {
System.out.println("Time's up!");
toolkit.beep();
//timer.cancel(); //Not necessary because we call System.exit
System.exit(0); //Stops the AWT thread (and everything else)
}
}
public static void main(String args[]) {
System.out.println("About to schedule task.");
new ReminderBeep(5);
System.out.println("Task scheduled.");
}
}
You can just use Thread.sleep() in your loop (if it's not on the main thread). Something like this (the code is not tested so may contain errors):
ExecutorService executorService = Executors.newFixedThreadPool(4);
for (int i = 0; i < 10; i++) {
executorService.execute(new Runnable() {
public void run() {
getData(String table);
}
Thread.sleep(10000);
}

Categories