nthportal / cancellable-task   1.0.0

Apache License 2.0 GitHub

A cancellable task to be run asynchronously.

Scala versions: 2.12 2.11

cancellable-task

A cancellable task to be run asynchronously.

Build Status Coverage Status Maven Central Versioning Docs

Add as a Dependency

SBT (Scala 2.11 and 2.12)

"com.nthportal" %% "cancellable-task" % "1.0.0"

Maven

Scala 2.12

<dependency>
  <groupId>com.nthportal</groupId>
  <artifactId>cancellable-task_2.12</artifactId>
  <version>1.0.0</version>
</dependency>

Scala 2.11

<dependency>
  <groupId>com.nthportal</groupId>
  <artifactId>cancellable-task_2.11</artifactId>
  <version>1.0.0</version>
</dependency>

Examples

import java.util.concurrent.TimeUnit

import com.nthportal.concurrent.CancellableTask
import scala.concurrent.ExecutionContext.Implicits.global

// Create a task
val task = CancellableTask {
  TimeUnit.MINUTES.sleep(5) // sleep thread for 5 minutes
  println("Done sleeping!")
  "the result of the task"
}

// Get a regular Scala Future with the result
val future = task.future
future.onComplete(t => {/* Do something with the Try */})

// Cancel the task, but do not interrupt if already started
val cancel1 = task.cancel(false)
val isCancelled1 = task.isCancelled
assert(cancel1 == isCancelled1)

// Cancel the task, and try to interrupt
val cancel2 = task.cancel(true)
val isCancelled2 = task.isCancelled
assert(isCancelled2 == cancel1 || cancel2) // was it cancelled one of the times?

Authorship

The core of this library was originally written by Stack Overflow user Pablo Francisco PĂ©rez Hidalgo (Twitter, GitHub). That implementation can be found on GitHub here, and in this Stack Overflow answer.

Stack Overflow user nightingale improved on the implementation by utilizing Java FutureTask's done() method; the improved implementation can be found in this Stack Overflow answer.

This author (NthPortal) tweaked the implementation by unwrapping ExecutionExceptions thrown by the FutureTask, and forwarding the cancel(boolean) and isCancelled() methods from FutureTask.