Bukkit runnable tips - java

Hello any ideas how to make scheduleSyncDelayedTask so it doesnt cancel previous task, which should be running and canceled a bit later?
for(int x = 0; x < 8; x++){
int taskID = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(Main.getPlugin(), new Runnable() {
#Override
public void run() {
CreateItems.createItemsOnStand2(player, bedna, listitems);
}
}, 30*x , 2+x);
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Main.getPlugin(), new Runnable() {
public void run() {
Bukkit.getScheduler().cancelTask(taskID);
}
}, (x==0) ? 30 : 30*x);
}

You can use BukkitRunnables for task scheduling
new BukkitRunnable() {
#Override
public void run() {
//Code you need running
this.cancel(); //Cancelling
}
}.runTaskTimer(pluginInstance, delayTime, repeatingTime);
new BukkitRunnable() {
#Override
public void run() {
//Code you need running
this.cancel(); //Cancelling
}
}.runTaskLater(pluginInstance, delayTime);
It makes it so the task can be easily created and self-cancellable

Related

Hot to use Thread in JAVA for EWS API?

I have below function for EWS JAVA API.
public static void cleanRootFolders(String account) throws Exception{
deleteEmailsFromInbox(account);
deleteEmailsFromDrafts(account);
deleteEmailsFromSentItems(account);
deleteEmailsFromJunkEmails(account);
deleteEventsFromCalendar(account);
deleteEmailsFromDeletedItems(account);
}
How can i Implement Thread for performing this Six methods simultaneously for saving the time instead of one after one ?
You can use a thread pool as follows:
ExecutorService executor = Executors.newFixedThreadPool(6);
Runnable r = new Runnable() {
#Override
void run() {
deleteEmailsFromInbox(account);
}
}
executor.execute(r)
r = new Runnable() {
#Override
void run() {
deleteEmailsFromDrafts(account);
}
}
executor.execute(r)
Or you could simply start a thread for each of the tasks:
Runnable r = new Runnable() {
#Override
void run() {
deleteEmailsFromInbox(account);
}
}
(new Thread(r)).start();
Below is complete code:
public static void cleanRootFolders(String account) throws Exception{
/*create number of threads = number of cores. Do note, creating 6 threads doesn't mean 6 threads will work simultaneously.*/
ExecutorService executor = Executors.newFixedThreadPool(numberOfCores);
executor.execute(new Runnable() {
public void run() {
deleteEmailsFromInbox(account);
}
});
executor.execute(new Runnable() {
public void run() {
deleteEmailsFromDrafts(account);
}
});
executor.execute(new Runnable() {
public void run() {
deleteEmailsFromSentItems(account);
}
});
executor.execute(new Runnable() {
public void run() {
deleteEmailsFromJunkEmails(account);
}
});
executor.execute(new Runnable() {
public void run() {
deleteEventsFromCalendar(account);
}
});
executor.execute(new Runnable() {
public void run() {
deleteEmailsFromDeletedItems(account);
}
});
executor.shutdown();
//always shutdown, so the threads do not keep running.
}

How can I execute this code 5 times with a 5 second delay between each execution?

package timerrr;
import java.util.*;
public class Timerrr {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(
new TimerTask() {
int i = 0;
#Override
public void run() {
System.out.println("timer is still running");
}
},
1 * 150 * 100,
1 * 50 * 100);
}
}
in your overridden run method increment i and if i = 5 cancel the timer:
timer.schedule(new TimerTask() {
int i = 0;
#Override
public void run() {
i++;
if(i==5) {
this.cancel();
}
else {
//YOUR CODE HERE
}
}
}, startDelay, fixedDelay);
Here should be an easier way to do what you want:
Calling the Thread.sleep(); method is, for some reason, one of my favorite things to call. You just have to surround it in a try/catch block like so:
public static void main(String[] args) {
for (int i = 0; i <= 5; i++) {
System.out.println("timer is still running");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
You may want to put that it it's own method with it's own thread, so that you can have other things running while this is happening.
Hope this helped :)

Threads running at specific time intervals for a specific time in JAVA

I want to use the below mentioned operations in JAVA for android development.
For 30 Seconds ,Run a Function F1() every 1 second (resulting in 30 F1 calls).
Run a Thread t1 forever
The above steps should execute sequentially.
I Have tried with ExecutorServicebut with no success.
This is my code for reference
final Handler h = new Handler();
final int delay = 1000; //milliseconds
ExecutorService executor = Executors.newFixedThreadPool(1);
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
F1();
}
});
for(int i=0;i<30;i++){
executor.submit(t1);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
executor.shutdown();
//Step 2 (THe Second Thread)
h.postDelayed(new Runnable() {
public void run() {
AnotherFunction()
h.postDelayed(this, delay);
}
}, delay);
Generally, ExecutorService is more preferable for such operations. Here is a good post describing the differences and features of Timer and ExecutorService.
As for your question directly - it can be implemented in such way:
// here are Runnables with test logic
Runnable foo = new Runnable() {
#Override
public void run() {
Log.d(">>>", "foo");
onTaskFinished();
}
};
Runnable longRunning = new Runnable() {
#Override
public void run() {
try {
Log.d(">>>", "longRunning started");
Thread.sleep(5000);
Log.d(">>>", "longRunning finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
// and here is valuable logic
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
ScheduledFuture<?> schedulerHandler;
volatile AtomicInteger tasksNum = new AtomicInteger(0);
private synchronized void onTaskFinished(){
if(tasksNum.incrementAndGet() >= 30){
scheduler.execute(new Runnable() {
#Override
public void run() {
schedulerHandler.cancel(true);
}
});
scheduler.execute(longRunning);
}
}
And then to start operation just invoke this command:
schedulerHandler = scheduler.scheduleAtFixedRate(foo, 0, 1, TimeUnit.SECONDS);
You may consider using the java.util.Timer and java.util.TimerTask classes
If you're doing what I think you're doing you can do as #erosb hinted, use Timer and TimerTask to schedule method executions at a fixed rate.
The following should work for you.
final int DELAY_BEFORE_START = 0;
final int RATE = 1000;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
F1();
}
}, DELAY_BEFORE_START, RATE);

Why is not my handler executing?

I have the following code:
int x=0;
private void startTimerThread() {
System.out.println("enter");
System.out.println("percentage"+percentage);
System.out.println("x"+x);
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
for (x = 0; x>= percentage; x++ ) {
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable(){
public void run() {
textpercentage.animate(x, x++);
System.out.println("enter"+x);
}
});
}
}
};
new Thread(runnable).start();
}
I am trying to animate digits on a textview using timely text view, however when I call startTimerThread from my code which is outside of onCreate neither do I get the text view to display not does the system.out execute. What do I miss here?
try like this
Handler handler = new Handler();
int delay=1000;
Runnable rann=new Runnable() {
#Override
public void run() {
//Write Your logic here which you want to perform periodically
System.out.println("Handler is running : ");
//to call the same thread repeatedly calling handler again
handler.postDelayed(rann, delay);
}
};
private void startHandler() {
//here the handler will executes the rannable after that particulary delay milli seconds
handler.postDelayed(rann, delay);
}
private void stopHandler() {
handler.removeCallbacks(rann);
}

I need to stop thread when progress bar reaches 0 in android

I need stop thread and handler when my progress bar reaches 0 from 100 when thread runs the progress bar reaches but the progressStatus value going in negative please help me to stop thread after progress bar reaches 0
new Thread(runn =new Runnable() {
public void run() {
while (progressStatus <= 100) {
progressStatus += doWork();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
handler.post(runn1=new Runnable() {
public void run() {
bar.setProgress(progressStatus);
i=-1;
if(bar.getProgress()==0)
{
handler.removeCallbacks(runn);
handler.removeCallbacks(runn1);
System.out.println("Reached");
congrats.setVisibility(View.VISIBLE);
restart.setVisibility(View.VISIBLE);
rightbutton.setVisibility(View.GONE);
wrongbutton.setVisibility(View.GONE);
}
}
});
}
}
private int doWork() {
return i;
}
}).start();
your program is not thread safe, you actually reading and writing a variable (progressStatus) from two different threads, you must avoid doing that or if you want to do that you must use synchronized block. In order to solve your problem you can do this way:
Thread t;
progressStatus = 100;
t = new Thread(runn =new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
// Update the progress bar
handler.post(runn1=new Runnable() {
public void run() {
bar.setProgress(progressStatus);
progressStatus=progressStatus-1;
if(bar.getProgress()==0)
{
handler.removeCallbacks(runn);
handler.removeCallbacks(runn1);
System.out.println("Reached");
congrats.setVisibility(View.VISIBLE);
restart.setVisibility(View.VISIBLE);
rightbutton.setVisibility(View.GONE);
wrongbutton.setVisibility(View.GONE);
t.interrupt();
}
}
});
another way that i recommend you is using ScheduledThreadPoolExecutor with the function scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit). something like:
final ScheduledThreadPoolExecutor myTimer = new ScheduledThreadPoolExecutor(1);
myTimer.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
getActivity().runOnUiThread(new Runnable(){
#Override
public void run(){
}
});
}
}
}, 0,10, TimeUnit.MILLISECONDS);
and in order to close it use myTimer.shutdownNow();

Categories