0

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

4 Answers4

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:

Community
  • 1
  • 1
itsadok
  • 27,343
  • 27
  • 120
  • 167
  • 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
  • 4,859
  • 3
  • 33
  • 64
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
  • 14,576
  • 2
  • 40
  • 62