Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to run the watcher? #25

Closed
simon-gunacker opened this issue Nov 2, 2018 · 3 comments
Closed

How to run the watcher? #25

simon-gunacker opened this issue Nov 2, 2018 · 3 comments

Comments

@simon-gunacker
Copy link

I am trying to run the watcher in Scala. But even though I am calling watcher.start() (which i expect to run forever), the program finishes immediately. What am I doing wrong?

import better.files._
import io.methvin.better.files._
import scala.concurrent.ExecutionContext.Implicits.global

object FileWatcher
{

  def main(args: Array[String]): Unit =
  {
    val myDir = File("/path/to/dir")
    val watcher = new RecursiveFileMonitor(myDir)
    {
      override def onCreate(file: File, count: Int) = println(s"$file got created")

      override def onModify(file: File, count: Int) = println(s"$file got modified $count times")

      override def onDelete(file: File, count: Int) = println(s"$file got deleted")
    }

    watcher.start()
  }

}
@gmethvin
Copy link
Owner

gmethvin commented Nov 3, 2018

start() works exactly like it does in the better-files File.Monitor it extends. It doesn't block. It runs the watch thread on the global execution context you've provided implicitly. The issue you're seeing is that your program is finishing immediately after the watcher starts running in the background.

@simon-gunacker
Copy link
Author

Yes. Non-blocking is a good thing for a file monitor ;-). But how can I run my program then? Let's just assume that it should not do anything else than printing the events ...

@gmethvin
Copy link
Owner

gmethvin commented Nov 4, 2018

The Scala global execution context sets threads to be daemon threads. The JVM will be shut down when all non-daemon threads have exited, so as soon as your main thread finishes, your watcher will be terminated. You either need some other non-daemon thread running doing your processing, or you need to use an execution context with non-daemon threads, for example:

implicit val ec: ExecutionContext =
  ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(8))

Hard to suggest specifics about thread pools without knowing the kind of work you're doing, but the bottom line is you need some regular non-daemon threads running so the JVM doesn't exit.

@gmethvin gmethvin closed this as completed Nov 4, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants