Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ////////////////////////////////////////////////////////////////////////////////////////////////////
- // Desc: Checks to see if this process is already running and if so, prevents this from running
- // Args: none
- // Ret : none - exits the applicaiton if an instance is already running
- ////////////////////////////////////////////////////////////////////////////////////////////////////
- public static void checkIfAlreadyRunning()
- {
- boolean running = false;
- String directoryLocation = "running_scripts/";
- String filename = directoryLocation + "my_application.txt";
- File scriptDir = new File(directoryLocation);
- // Create the directory structure if it doesn't exist.
- if (!scriptDir.exists())
- {
- scriptDir.mkdirs();
- }
- // Create the file if it doesnt exist.
- File scriptFile = new File(filename);
- if (!scriptFile.exists())
- {
- try
- {
- scriptFile.createNewFile();
- }
- catch (Exception e)
- {
- System.out.println("Error creating script file that didnt exist: " + e);
- System.exit(1);
- }
- }
- // If can get a lock on the file then this process is not already running.
- try
- {
- FileChannel channel = new RandomAccessFile(scriptFile, "rw").getChannel();
- FileLock lock = channel.tryLock();
- // Trylock returns null if overlapping lock, not an error
- if (lock == null)
- {
- String message = "You are only allowed to have one running instance of " +
- "this app.";
- System.out.println(message);
- System.exit(0);
- }
- }
- catch (Exception p)
- {
- System.out.println("checkIfAlreadyRunning Error " + p);
- System.exit(1);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement