Im currently writing a program that runs a class that implements runnable.
I have it so the time in a format of HH:MM:SS is printed to the screen every second.
Heres the code:
public class LaunchCounter
{
public static void main(String[] args)
{
//Runs the CounterThread
new CounterThread().start();
}
}
And here is the counter class
public class CounterThread implements Runnable
{
//Declare new thread
private Thread thread;
public void start()
{
thread = new Thread(this, "");
thread.start();
}
#Override
public void run()
{
//Formatter used to display just time not date
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
//never ending forloop to display time
for(int i = 1; i > 0; i++)
{
try
{
//Runtime.getRuntime().exec( "cmd /c cls" );
//Sleep for 1 second after each loop
Thread.sleep(1000);
//new calender is created
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
}
catch(Exception e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
This works perfectly fine.
What i am trying to achieve is that the line that is printed is cleared after waiting a second, and the the new time is printed and so on.
So 12:00:01 becocomes 12:00:02 with out taking a new line.
I've tried System.out.print("\b\b\b\b\b\b\b") and Runtime.getRuntime().exec( "cmd /c cls" ); But this is just printing squares to the console.
How would i achieve this?
The problem is the terminal you're using. (My guess is that you are using the terminal in your IDE.) If your output terminal doesn't do full terminal emulation, it will either ignore the \b characters or display them as unprintable characters.
I tested the following code in IntelliJ IDEA 16 and verified that \b is ignored by the built in IDEA terminal. I then tested it in the MacOS terminal and it worked the way you want it to.
package test;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class CounterThread implements Runnable {
//Declare new thread
private Thread thread;
public void start() {
thread = new Thread(this, "");
thread.start();
}
#Override
public void run() {
//Formatter used to display just time not date
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
//never ending forloop to display time
for (int i = 1; i > 0; i++) {
try {
//Runtime.getRuntime().exec( "cmd /c cls" );
//Sleep for 1 second after each loop
Thread.sleep(1000);
//new calender is created
Calendar cal = Calendar.getInstance();
System.out.print("\b\b\b\b\b\b\b\b");
System.out.print(dateFormat.format(cal.getTime()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public static void main(String[] args) throws Exception {
//Runs the CounterThread
new CounterThread().start();
final Object monitor = new Object();
synchronized (monitor) {
monitor.wait();
}
}
}
You're on the right track using Runtime.getRuntime().exec("cls");. See this post here by Holger for maybe why you're not able to clear the console.
To solve this problem, we have to invoke the command line interpreter
(cmd) and tell it to execute a command (/c cls) which allows invoking
builtin commands. Further we have to directly connect its output
channel to the Java process’ output channel, which works starting with
Java 7, using inheritIO():
import java.io.IOException;
public class CLS {
public static void main(String... arg) throws IOException, InterruptedException {
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
}
}
Now when the Java process is connected to a console, i.e. has been
started from a command line without output redirection, it will clear
the console.
Related
I have written a simple script to output a KeyPress message; it repeats with a do-while loop but never terminates. I want to terminate it after 15 seconds, but none of the commands I've tried have worked. At present, all it does is lock up the executing device with infinite reputations of "HAPPY BIRTHDAY", increasing RAM usage until it crashes. The script is below;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
public class robot {
private static boolean yes;
public static void main(String[] args) throws AWTException, InterruptedException {
yes=(true);
// TODO Auto-generated method stub
do {
Robot r = new Robot();
r.keyPress(KeyEvent.VK_H);
r.keyRelease(KeyEvent.VK_H);
r.keyPress(KeyEvent.VK_A);
r.keyRelease(KeyEvent.VK_A);
r.keyPress(KeyEvent.VK_P);
r.keyRelease(KeyEvent.VK_P);
r.keyPress(KeyEvent.VK_P);
r.keyRelease(KeyEvent.VK_P);
r.keyPress(KeyEvent.VK_Y);
r.keyRelease(KeyEvent.VK_Y);
r.keyPress(KeyEvent.VK_SPACE);
r.keyRelease(KeyEvent.VK_SPACE);
r.keyPress(KeyEvent.VK_B);
r.keyRelease(KeyEvent.VK_B);
r.keyPress(KeyEvent.VK_I);
r.keyRelease(KeyEvent.VK_I);
r.keyPress(KeyEvent.VK_R);
r.keyRelease(KeyEvent.VK_R);
r.keyPress(KeyEvent.VK_T);
r.keyRelease(KeyEvent.VK_T);
r.keyPress(KeyEvent.VK_H);
r.keyRelease(KeyEvent.VK_H);
r.keyPress(KeyEvent.VK_D);
r.keyRelease(KeyEvent.VK_D);
r.keyPress(KeyEvent.VK_A);
r.keyRelease(KeyEvent.VK_A);
r.keyPress(KeyEvent.VK_Y);
r.keyRelease(KeyEvent.VK_Y);
} while (yes==true);
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
yes=false;
}
},
5000
);
}}
Advice on either a better loop or how to terminate after a set time is appreciated.
Here is another way to do it, using LocalTime
LocalTime now = LocalTime.now();
LocalTime later = now.plusSeconds(5);
int count = 0;
while (now.isBefore(later)){
System.out.println(count++);
Thread.sleep(1000);
now = LocalTime.now();
}
I am trying to switch from eclipse to IntelliJ and first thing I wanted to check was debugging Multi-Thread programs. I implemented a simple program written below.
class VolatileExample extends Thread {
private volatile boolean running = true;
public void run() {
while (running) {
System.out.println("Hello");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void stopThread() {
running = false;
}
}
class Runner {
public static void main(String args[]) {
VolatileExample obj = new VolatileExample();
Thread t1 = new Thread(obj);
t1.start();
**//**BREAKPOINT****
Scanner sc = new Scanner(System.in);
sc.nextLine();
obj.stopThread();
}
}
Now when I debug this code in eclipse , breakpoint I have commented in the program, the main thread stays in suspended state while Thread executes and I get Hello running multiple times on the console
But as with IntelliJ, there is no output on the console, giving a view as if Thread is in suspended state.
Kindly help me with this debugging.I guess I am doing something wrong.
I'm trying to write a program that runs one of three functions, depending on which button is pressed by the user. The third function should run in an endless loop until the user interrupts it somehow. However, I'm struggling to code this. I tried to write a while(System.in.available() == 0) loop, but when I press Enter while that part of the program is active, it simply does nothing. Here is the part of my code that I think is relevant:
public static void main(String[] args) {
new WaspmoteSim();
}
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("Demonstration Mode")) {
DemoMethod();
}
if (command.equals("Distribution Fitting Mode")) {
FittingMethod();
}
if (command.equals("Operational Mode")) {
OperationsMethod();
}
}
public void OperationsMethod() throws IOException, InterruptedException {
Process proc;
while(System.in.available() == 0) {
String workingDir = System.getProperty("user.dir");
System.out.println(workingDir);
proc = Runtime.getRuntime().exec("cmd.exe /C C:\\Progra~1\\R\\R-3.2.1.\\bin\\Rscript.exe " + workingDir + "\\Fitter.r");
TimeUnit.SECONDS.sleep(8);
}
}
and the WaspmoteSim function's declaration is:
public class WaspmoteSim extends JFrame implements ActionListener {
Do you guys have any ideas?
I have an old application that has a robot thread that executes everyday. I have the source for the robot, but I don't know how this tread is started. And there's a log, witch includes a line in a database, that sometimes includes 2 identical lines, proving that the process is executing doubled.
we use Windows Server 2003
public void run()
{
while (true)
{
starter();
try {
Thread.sleep(10800000L);
}
catch (InterruptedException localInterruptedException)
{
}
}
}
I need to keep it from executing more than once.
I'm new to treads, don't really get the works of a thread right yet...
thank you all in advance...
You don't really provide a lot of information, but here are a few guesses:
Could the entire process be launched twice?
If the thread is running twice, showing the thread run function won't help. You'll have to find the code that creates the thread.
Log something in the catch block. Maybe a sleep call gets interrupted immediately and this is why starter() is called twice at almost the same time.
public void run()
{
int delay = 86400000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
starter();
}
};
new Timer(delay, taskPerformer).start();
}
Or...
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class DailyTask extends TimerTask {
#Override
public void run() {
//Or if you use a logger like log4j you can insert logger code here.
System.out.println("Start:" + new Date());
starter();
System.out.println("End:" + new Date());
}
public static void main(String args[]) {
TimerTask tt= new DailyTask();
// running timer task as daemon thread
Timer t = new Timer(true);
t.scheduleAtFixedRate(tt, 0, 86400000);
System.out.println("DailyTask started:" + new Date());
}
}
This should run starter() once every 24 hours.
I'm trying to use a Bukkit conversation, which already works, yet, when I use TimeUnit.SECONDS.sleep(integer-value), it works once, and then it fails with this error in console: java.lang.InterruptedException: sleep interrupted
When a prompt has been shown and the next is going to be shown the method acceptInput is called. In the first prompt it works all fine, in the other prompts, which are called out of this prompt (the prompt calls a new instance of itself). All works fine except the sleep part. Any ideas to fix this?
Here is my code:
package dbx12.Test1.Tutorial.Prompts;
import java.util.concurrent.TimeUnit;
import org.bukkit.conversations.ConversationContext;
import org.bukkit.conversations.Prompt;
import org.bukkit.entity.Player;
public class Text implements Prompt {
#Override
public Prompt acceptInput(ConversationContext context, String input) {
int thisPrompt = (int) context.getSessionData("step");
context.setSessionData("step", thisPrompt+1);
Player p = (Player) context.getForWhom();
boolean type;
try {
TimeUnit.SECONDS.sleep(dbx12.Test1.Utils.Prompt_List.delay.get(thisPrompt));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace(); //DEBUG
}
try {
type = dbx12.Test1.Utils.Prompt_List.promptType.get(thisPrompt+1);
} catch (Exception e) {
return new Finish();
}
if(dbx12.Test1.Utils.Prompt_List.hasLocation.get(thisPrompt+1) == true)
p.teleport(dbx12.Test1.Utils.Prompt_List.location.get(thisPrompt+1));
if(type==true)
{
System.out.println("return a text");
return new Text();
}
else
{
System.out.println("return a interaction");
return new Interaction();
}
}
#Override
public boolean blocksForInput(ConversationContext context) {
return false;
}
#Override
public String getPromptText(ConversationContext context) {
return dbx12.Test1.Utils.Prompt_List.promptText.get(context.getSessionData("step"));
}
}
sleep will cause your entire server to stop doing anything for x seconds. Instead of sleep, use a SyncDelayedTask:
this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable(){
public void run(){
//what you want to do here
}
},delayInSeconds * 20);
so, lets say for example you wanted to send test1 to the server, then test2 to the server 5 seconds later, you could use:
int repeats;
public void sendMessages(){
this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable(){
public void run(){
if(repeats == 0){ //if it's the first time running
Bukkit.getServer.broadcastMessage("test1");
repeats++; //add to repeats
sendMessages(); //call the method again
}
else if(repeats == 1){ //if it is the second time being called
Bukkit.getServer.broadcastMessage("test2");
}
}
},5 * 20);//wait 5 seconds
so with the above code, you could make a method like this:
public void startSendingMessages(){
repeats = 0;
sendMessages();
}
Where when you called startSendingMessages(), the test1 would be sent, then, 5 seconds later, test2 would be sent.
The reason we are multiplying the time in seconds by 20, is because it has to be in ticks, or minecraft time, and 1 second = 20 ticks.
There's lots of other scheduler types, like SyncRepeatingTasks. To learn more about them, check out the bukkit JavaDocs: http://jd.bukkit.org/dev/apidocs/, theres also a nice tutorial from bukkit here: http://wiki.bukkit.org/Scheduler_Programming