When I start TimerTask and then I finish, and then start again it shows this error, why?
this error:
[16:30:02] [Client thread/INFO] [MacroSK]: KEY_L
[16:30:06] [Client thread/INFO] [MacroSK]: KEY_O
[16:30:08] [Client thread/INFO] [MacroSK]: KEY_L
[16:30:08] [Client thread/ERROR] [FML]: Exception caught during firing event net.minecraftforge.fml.common.gameevent.TickEvent$ClientTickEvent#1bc14017:
java.lang.IllegalStateException: Task already scheduled or cancelled
at java.util.Timer.sched(Unknown Source) ~[?:1.8.0_161]
at java.util.Timer.scheduleAtFixedRate(Unknown Source) ~[?:1.8.0_161]
at com.skelletonx.MacroSK.handler.KeybindHandler.Shopmsg(KeybindHandler.java:53) ~[KeybindHandler.class:?]
at com.skelletonx.MacroSK.handler.KeybindHandler.onTickEvent(KeybindHandler.java:63) ~[KeybindHandler.class:?]
at net.minecraftforge.fml.common.eventhandler.ASMEventHandler_6_KeybindHandler_onTickEvent_ClientTickEvent.invoke(.dynamic) ~[?:?]
at net.minecraftforge.fml.common.eventhandler.ASMEventHandler.invoke(ASMEventHandler.java:55) ~[ASMEventHandler.class:?]
at net.minecraftforge.fml.common.eventhandler.EventBus.post(EventBus.java:140) [EventBus.class:?]
at net.minecraftforge.fml.common.FMLCommonHandler.onPostClientTick(FMLCommonHandler.java:371) [FMLCommonHandler.class:?]
at net.minecraft.client.Minecraft.func_71407_l(Minecraft.java:2152) [bsu.class:?]
at net.minecraft.client.Minecraft.func_71411_J(Minecraft.java:1028) [bsu.class:?]
at net.minecraft.client.Minecraft.func_99999_d(Minecraft.java:345) [bsu.class:?]
at net.minecraft.client.main.Main.main(SourceFile:120) [Main.class:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_161]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_161]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_161]
at java.lang.reflect.Method.invoke(Unknown Source) ~[?:1.8.0_161]
at net.minecraft.launchwrapper.Launch.launch(Launch.java:135) [launchwrapper-1.12.jar:?]
at net.minecraft.launchwrapper.Launch.main(Launch.java:28) [launchwrapper-1.12.jar:?]
my code :
Timer timer = new Timer();
final TimerTask ts = new TimerTask(){
#Override
public void run() {
Minecraft.getMinecraft().thePlayer.sendChatMessage(Ini.getIni("Loja"));
}
};
int delaymsg = Integer.parseInt(Ini.getIni("DelayL"));
public void Shopmsg() {
timer.scheduleAtFixedRate(ts,1000*delaymsg,1000*delaymsg);
}
#SideOnly(Side.CLIENT)
#SubscribeEvent(priority=EventPriority.NORMAL, receiveCanceled=true)
public void onTickEvent(TickEvent.ClientTickEvent event) {
if(event.phase == TickEvent.Phase.END) {
if (mc.inGameHasFocus) {
if (keyBindings[0].isPressed()) {
LogHelper.info("KEY_L");
Shopmsg();
}
if(keyBindings[1].isPressed()) {
LogHelper.info("KEY_O");
ts.cancel();
}
}
}
}
how can I do that when I finish TaskTime, I can start again?
if not stop, stop and restart the tasktime is it possible to pause and resume?
TimerTask can only be scheduled by a Timer once.
Continuing working with Timer, you would need to recreate a new TimerTask ts each time in ShopMsg().
It's worth saying though that Timer has been superseded by ScheduledExecutorService these days. This is generally more flexible...
E.g. to create the executor (in place of Timer):
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
Then to schedule the loop:
ScheduledFuture<?> future = scheduledExecutorService.scheduleAtFixedRate(
() -> Minecraft.getMinecraft().thePlayer.sendChatMessage(Ini.getIni("Loja")),
delaymsg,
delaymsg,
TimeUnit.SECONDS);
And to stop that schedule:
future.cancel(false);
How about this closure-like approach:
(high-level code but still cute and workable)`
...
<inside method>
...
class NewTimerTask extends TimerTask {
#Override
public void run() {
actionToBePerformed.run();
timer.schedule(new TimerTask() {
#Override
public void run() {
NewTimerTask.this.run();
}
}, countOffset(morningHour, eveningHour));
}
}
timer.schedule(new NewTimerTask(), countOffset(morningHour, eveningHour));
I always create a new TimerTask instance and then schedule it with the same instance one of Timer. There are no issues but still I had one report from Firebase Crashlytics and I think it's related to Thread termination of timer:
So it has nothing to do with reusing the same instance of TimerTask cause in my case it's not possible!
So mb we need to recreate Timer instance in try...catch
Related
I am using ignite 2.8.1 I have ignite lock that is inside some cron, I use it to run my processing only on single server node.I have 3 server nodes in my app.
And today I've seen some exceptions. Could you explain how it could happens? It seems it happens while unlock(), but it is strange how it could not own the lock if is inside tryLock() ?
<ignite-sys-atomic-cache#default-volatile-ds-group> Lock.unlock() is called in illegal state [callerNodeId=ee0de9a9-5a13-4971-a744-dcc5087fd287, ownerNodeId=a2bba513-9ed7-4dc3-beea-574bf46f0034, callerThreadId=674, ownerThreadId=672, lockState=1]
ant trace:
java.lang.IllegalMonitorStateException: null at org.apache.ignite.internal.processors.datastructures.GridCacheLockImpl$Sync.tryRelease(GridCacheLockImpl.java:446) at
java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1261) at
org.apache.ignite.internal.processors.datastructures.GridCacheLockImpl.unlock(GridCacheLockImpl.java:1258) at com.sa.sm.vp.service.LockUtil.unlock(LockUtil.java:35) at
com.sa.sm.vp.service.content.SessionExpirator.triggerExpirationEvent(SessionExpirator.java:78) at
com.sa.sm.vp.service.content.SessionExpirator$$FastClassBySpringCGLIB$$ac2d1b1f.invoke(<generated>) at
org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) at
org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771) at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) at
org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749) at
org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:88) at
io.opentracing.contrib.spring.cloud.scheduled.ScheduledAspect.traceBackgroundThread(ScheduledAspect.java:57) at
sun.reflect.GeneratedMethodAccessor117.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:644) at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:633) at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroun
code:
private IgniteSpringBean igniteSpringBean;
#Scheduled(initialDelay = 20000, fixedDelay = 4000)
#Timed
public void triggerExpirationEvent() {
IgniteLock lock = igniteSpringBean.reentrantLock("PLAYBACK_SESSION", true, true, true);
if (lock.tryLock()) {
try {
// do my work in separate thread
// timeout
try {
TimeUnit.MICROSECONDS.sleep(2000);
} catch (InterruptedException e) {
log.warn("Failed to sleep ", e);
}
}
} finally {
lock.unlock()
}
}
}
I'm relatively new (about 1 month) to JavaFX, and even newer to Gradle. My project is here, on Github. When I run ./gradlew build, it works fine. But, when I run ./gradlew run , I get all this:
Alins-MacBook-Pro:evisu Alin$ ./gradlew run
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:cssToBin SKIPPED
:classes UP-TO-DATE
:run
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$152(LauncherImpl.java:182)
at com.sun.javafx.application.LauncherImpl$$Lambda$51/1323468230.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException: inputStream is null.
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2459)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2429)
at ro.badilos.evisu.EviSU.loadMainPane(EviSU.java:43)
at ro.badilos.evisu.EviSU.start(EviSU.java:27)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$159(LauncherImpl.java:863)
at com.sun.javafx.application.LauncherImpl$$Lambda$54/2140593657.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$172(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl$$Lambda$47/186276003.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$170(PlatformImpl.java:295)
at com.sun.javafx.application.PlatformImpl$$Lambda$49/1714838540.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$171(PlatformImpl.java:294)
at com.sun.javafx.application.PlatformImpl$$Lambda$48/237061348.run(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
Exception running application ro.badilos.evisu.EviSU
:run FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':run'.
> Process 'command '/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home/bin/java'' finished with non-zero exit value 1
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Total time: 3.74 secs
What am I doing wrong?
Is this the base of all the problems?
Caused by: java.lang.NullPointerException: inputStream is null.
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2459)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2429)
at ro.badilos.evisu.EviSU.loadMainPane(EviSU.java:43)
at ro.badilos.evisu.EviSU.start(EviSU.java:27)
What would be the correct path to the .fxml files?
Thank you!
Yes, the NullPointerException is the root cause of the whole problem. You red resources incorrectly. Please replace this line (in class ro.badilos.evisu.EviSU:
Pane mainPane = (Pane) loader.load(getClass().getResourceAsStream(VistaNavigator.MAIN));
with the following one:
Pane mainPane = (Pane) loader.load(getClass().getClassLoader().getResourceAsStream(VistaNavigator.MAIN));
And change the following lines in ro.badilos.evisu.VistaNavigator:
public static final String MAIN = "src/main/resources/Main.fxml";
public static final String VISTA_1 = "src/main/resources/NewSU.fxml";
public static final String VISTA_2 = "src/main/resources/NewSMURD.fxml";
to:
public static final String MAIN = "Main.fxml";
public static final String VISTA_1 = "NewSU.fxml";
public static final String VISTA_2 = "NewSMURD.fxml";
After introducing these changes all resources will be read correctly. Running gradle clean run still results in exception but this is another one.
To fix the new exception change (in ro.badilos.evisu.VistaNavigator):
public static void loadVista(String fxml) {
try {
mainController.setVista(
(Node) FXMLLoader.load(
VistaNavigator.class.getResource(
fxml
)
));
} catch (IOException e) {
e.printStackTrace();
}
}
to:
public static void loadVista(String fxml) {
try {
mainController.setVista(
(Node) FXMLLoader.load(
VistaNavigator.class.getClassLoader().getResource(
fxml
)
));
} catch (IOException e) {
e.printStackTrace();
}
}
Remember to always refer to resources via ClassLoader. Now it runs, however another NPE is printed to console.
EDIT
Ok, the final NPE is cause by:
#Override
public void initialize(URL location, ResourceBundle resources) {
try {
Image focIcon = new Image(getClass().getResourceAsStream("pool/foc16px.png"));
btnNewSU.setGraphic(new ImageView(focIcon));
Image smurdIcon = new Image(getClass().getResourceAsStream("pool/smurd16px.png"));
btnNewSMURD.setGraphic(new ImageView(smurdIcon));
} catch (Exception e) {
e.printStackTrace();
}
}
Should be:
#Override
public void initialize(URL location, ResourceBundle resources) {
try {
Image focIcon = new Image(getClass().getClassLoader().getResourceAsStream("foc16px.png"));
btnNewSU.setGraphic(new ImageView(focIcon));
Image smurdIcon = new Image(getClass().getClassLoader().getResourceAsStream("smurd16px.png"));
btnNewSMURD.setGraphic(new ImageView(smurdIcon));
} catch (Exception e) {
e.printStackTrace();
}
}
And the last thing, you need to fix the reference to Nomeclator.db in ro.badilos.controller.InfoSituatiaProdusaController as well.
I'm trying to set the string of a Text object from a Thread but it's giving me this error:
Exception in thread "Thread-4" java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-4
at com.sun.javafx.tk.Toolkit.checkFxUserThread(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(Unknown Source)
at javafx.scene.Scene.addToDirtyList(Unknown Source)
at javafx.scene.Node.addToSceneDirtyList(Unknown Source)
at javafx.scene.Node.impl_markDirty(Unknown Source)
at javafx.scene.shape.Shape.impl_markDirty(Unknown Source)
at javafx.scene.Node.impl_geomChanged(Unknown Source)
at javafx.scene.text.Text.impl_geomChanged(Unknown Source)
at javafx.scene.text.Text.needsTextLayout(Unknown Source)
at javafx.scene.text.Text.needsFullTextLayout(Unknown Source)
at javafx.scene.text.Text.access$200(Unknown Source)
at javafx.scene.text.Text$2.invalidated(Unknown Source)
at javafx.beans.property.StringPropertyBase.markInvalid(Unknown Source)
at javafx.beans.property.StringPropertyBase.set(Unknown Source)
at javafx.beans.property.StringPropertyBase.set(Unknown Source)
at javafx.scene.text.Text.setText(Unknown Source)
at uy.com.vincent.fx.handling.TableController$1.run(TableController.java:70)
Handler Class:
#FXML
private Text timer;
#Override
public void initialize(URL url, ResourceBundle rb) {
init();
new Thread() {
public void run() {
while(true) {
Calendar cal = new GregorianCalendar();
int hour = cal.get(cal.HOUR);
int minute = cal.get(cal.MINUTE);
int second = cal.get(cal.SECOND);
int AM_PM = cal.get(cal.AM_PM);
String time = hour + "" + minute + "" + second;
timer.setText(time);
}
}
}.start();
}
I'm following a tutorial.
The guy in the tutorial is not using JavaFX.
I have tried using Platform.runLater(), it does work but it crashes my program.
I also tried creating a Timer on the Platform.runLater(new Runnable() { }) method but it gives me the same error as before.
Wrap timer.setText() in Platform.runLater(). Outside it, inside the while loop, add Thread.sleep(1000);
The reason behind Illegal State Exception is you are trying to update UI on some thread other than JavaFX Application thread.
The reason why your app was crashing when you added it was you were overloading the UI thread by adding a process to be executed on the UI thread infinitely. Making the thread sleep for 1000ms will help you overcome the issue.
If possible replace while(true) with a Timer or TimerTask.
For more options follow this link
I have this one:
while(SD.SessionAlive)
{
timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
try
{
SD.closeSession();
}
catch(Exception e)
{
}
}
}, timeToRun);
String InputData = SD.ClientSocketReader.readLine();
timer.cancel();
if(InputData!=null)
{
commandHandler(InputData);
}
}
In this case, I need listen input data from BufferedReader.
If client dont send anything, after 30 seconds, session must be closed.
When I use no SSL conenction, I close session using shutdownInput and shutdownOutput.
But when I use SSL connection, I can use shutdownInput and shutdownOutput: "The method shutdownInput() is not supported in SSLSocket".
And when I use BufferedReader.close(), session wait closing....
Name: smie
State: RUNNABLE
Total blocked: 0 Total waited: 0
Stack trace:
java.net.SocketInputStream.socketRead0(Native Method)
java.net.SocketInputStream.read(SocketInputStream.java:129)
com.sun.net.ssl.internal.ssl.InputRecord.readFully(InputRecord.java:293)
com.sun.net.ssl.internal.ssl.InputRecord.read(InputRecord.java:331)
com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:798)
- locked java.lang.Object#37f8d244
com.sun.net.ssl.internal.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:755)
com.sun.net.ssl.internal.ssl.AppInputStream.read(AppInputStream.java:75)
- locked com.sun.net.ssl.internal.ssl.AppInputStream#30b48b11
sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:264)
sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306)
sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158)
- locked java.io.InputStreamReader#2fa6a1a7
java.io.InputStreamReader.read(InputStreamReader.java:167)
java.io.BufferedReader.fill(BufferedReader.java:136)
java.io.BufferedReader.readLine(BufferedReader.java:299)
- locked java.io.InputStreamReader#2fa6a1a7
java.io.BufferedReader.readLine(BufferedReader.java:362)
org.smie.ftpex.SessionHandler.run(SessionHandler.java:71)
where SessionHandler.java:71 is:
String InputData = SD.ClientSocketReader.readLine();
How I can close in and out streams?
I'm trying to do a little program in Java using Eclipse, and I'm a little bit lost.
Could anybody explain me (in a "for dummies way") what do I have to do for repaint a form using a timer?
I'm trying to do something as simple as a clock. I need a timer to repaint it every second.
Something like this:
private void activateTimer()
{
ActionListener myAction;
myAction = new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
whatever.redraw();
}
};
myTimer = new Timer(1000, myAction);
myTimer.start();
}
When the action must be performed, I receive the error:
*Exception in thread "AWT-EventQueue-0" org.eclipse.swt.SWTException: Invalid thread access*
This is the full exception I receive:
Exception in thread "AWT-EventQueue-0" org.eclipse.swt.SWTException: Invalid thread access
at org.eclipse.swt.SWT.error(SWT.java:4282)
at org.eclipse.swt.SWT.error(SWT.java:4197)
at org.eclipse.swt.SWT.error(SWT.java:4168)
at org.eclipse.swt.widgets.Widget.error(Widget.java:468)
at org.eclipse.swt.widgets.Widget.checkWidget(Widget.java:359)
at org.eclipse.swt.widgets.Control.redraw(Control.java:2327)
at default.myTimer$1.actionPerformed(myTimer.java:97)
at javax.swing.Timer.fireActionPerformed(Unknown Source)
at javax.swing.Timer$DoPostEvent.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Any idea or any sample about refreshing a screen every second?
I've followed the instructions in one of the answers but I'm still receiving the same error.
you have to split that to the separete methods, better would be using javax.swing.Action instead of ActionListener
private void activateTimer(){
myTimer = new Timer(1000, myAction);
myTimer.start();
}
private Action myAction = new AbstractAction() {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
whatever.redraw();
}
};
Why not use the timer functionality that is built into the SWT Display class?
private void activateTimer(final Display display)
{
display.timerExec(
1000,
new Runnable() {
public void run() {
whatever.redraw();
// If you want it to repeat:
display.timerExec(1000, this);
}
});
}
This page may be useful.
If you use SWT, do it in SWT way :)
EDIT:
The problem is widget should be updated by eclipse's thread. Try this code.
Job job = new Job("My Job") {
#Override
protected IStatus run(IProgressMonitor monitor) {
Display.getDefault().asyncExec(new Runnable() {
#Override
public void run() {
while(true)
{
Thread.sleep(1000);
whatever.redraw();
}
}
});
return Status.OK_STATUS;
}
};
job.schedule();