I am new in java I am searching for a background thread in java which runs periodically even after the java desktop app is closed. I need a thing similar to Service in Android . I searched for it but I found just threads no service. I have to send data to the server which will be store in config.propertise file through that background Thread or Service. Thanks in Advance
Asked
Active
Viewed 575 times
0
-
1http://stackoverflow.com/questions/68113/how-to-create-a-windows-service-from-java-app - Does this help? – BatScream Nov 12 '14 at 06:35
-
Thanks but This is not that service – Nov 12 '14 at 06:37
-
1Uhh, you're wrong, that's what you need. – djechlin Nov 12 '14 at 06:52
4 Answers
5
A thread is contained within a process, so it doesn't make sense to talk about threads that run after the app is closed.
You either want:
- A separate service, like @BatScream suggested, which is a process that runs in the background without an app window connected to it.
- A scheduled task that uses Windows scheduled tasks mechanism to run some process periodically. See Running a JAVA program as a scheduled task
- Or you want your app to minimize to the tray. See How do I put a Java app in the system tray?
-
okay supppose I had made the Windows service following http://joerglenhard.wordpress.com/2012/05/29/build-windows-service-from-java-application-with-procrun/ Now where can I write the code which sends data to the server periodically even after the app is closed – Nov 12 '14 at 07:19
1
You can achieve the same thing by using a timer class. O.w background services are here How to create a windows service from java app

Community
- 1
- 1
0
I have a unusual way to do it. it work for me always. You have to do a certain task after the user close the app, Right??? . Just override the close button functionality and hide the window on close action. And continue your work in thread. When your work is finished close your app using
System.exit
User will never know that the app is running in background.

Syeda Zunaira
- 5,191
- 3
- 38
- 70
-
There are better answers than this. Why is this the accepted answer or be worth a bounty? – Mike Laren Dec 12 '14 at 00:42
-
0
Base one this, create a Java program, which will be used as a service with Linux crontab or Windows scheduler.
public class SomeService
{
// Your task will repeat itself periodically (here every minute), until it is stopped
private static final int SLEEP_TIME = 60000;
private static boolean stop = false;
public static void start(String[] args)
{
System.out.println("start");
while (!stop)
{
sendDataToServer();
try
{
Thread.sleep(SLEEP_TIME);
}
catch (InterruptedException e) {}
}
}
private void sendDataToServer()
{
// TODO your job here
}
public static void stop(String[] args)
{
System.out.println("stop");
stop = true;
}
public static void main(String[] args)
{
if ("start".equals(args[0]))
{
start(args);
}
else if ("stop".equals(args[0]))
{
stop(args);
}
}
}

ToYonos
- 16,469
- 2
- 54
- 70