/* Copyright 1999-2008 Acelet.org. All rights reserved. GPL v2 license */
/** @author Wei Jiang */

package com.acelet.s.watchdog;

import java.io.*;

import com.acelet.s.chore.Chore;

// This example watches a file "ExampleUserTriggeringFile" in the current directory. 
// If the file exists, it triggers and delete the file immediately.
// How to test:
// Set a task with this trigger. Whenever a file by the name is created. The task 
// will be triggered. 
// The binary class file is included in the installation on the CLASSPATH. 
// You can use it directly.

public class ExampleUserTriggering implements Runnable, Triggering {
  Watchable watchable;
  boolean alive = true;

  String fileName = "ExampleUserTriggeringFile";
  File theFile;
  long triggerTime;

  public ExampleUserTriggering() {
  }

  public String getTriggerStamp() {
    return "";
  }

  public long getTriggerTime() {
    return triggerTime;
  }

  public void removeListener(Watchable watchable) {
    watchable = null;
  }

  public void run() {
    while (alive) {
      try {
        theFile = new File(fileName);
        if (theFile.exists()) {
          theFile.delete();
          triggerTime = System.currentTimeMillis();
          watchable.startTask();
        }
        Thread.currentThread().sleep(5000);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    try {
      Thread.sleep(Watchdogging.interval);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  public void setListener(Watchable watchable, Chore comingChore) throws Exception {
    this.watchable = watchable;

    Thread thread = new Thread(this);
    thread.start();
  }

  public void stop() throws Exception {
    alive = false;
  }
}


