# Define a task to run in parallel.
task <- function(x, y) {
# Sleep a bit.
Sys.sleep(0.15)
# Return the result of a computation.
return(x + y)
}
# Create a specification object.
specification <- Specification$new()
# Set the number of cores.
specification$set_cores(cores = 2)
# Set the cluster type.
specification$set_type(type = "psock")
# Create a backend factory.
backend_factory <- BackendFactory$new()
# Get a backend instance that does not support progress tracking.
backend <- backend_factory$get("sync")
# Create a progress tracking context object.
context <- ProgressTrackingContext$new()
# Attempt to set the incompatible backend instance.
try(context$set_backend(backend))
# Get a backend instance that does support progress tracking.
backend <- backend_factory$get("async")
# Register the backend with the context.
context$set_backend(backend)
# From now all, all backend operations are intercepted by the context.
# Start the backend.
context$start(specification)
# Create a bar factory.
bar_factory <- BarFactory$new()
# Get a modern bar instance.
bar <- bar_factory$get("modern")
# Register the bar with the context.
context$set_bar(bar)
# Configure the bar.
context$configure_bar(
show_after = 0,
format = " > completed :current out of :total tasks [:percent] [:elapsed]"
)
# Run a task in parallel (i.e., approx. 1.9 seconds).
context$sapply(x = 1:25, fun = task, y = 10)
# Get the task output.
backend$get_output(wait = TRUE)
# Change the bar type.
bar <- bar_factory$get("basic")
# Register the bar with the context.
context$set_bar(bar)
# Remove the previous bar configuration.
context$configure_bar()
# Run a task in parallel (i.e., approx. 1.9 seconds).
context$sapply(x = 1:25, fun = task, y = 10)
# Get the task output.
backend$get_output(wait = TRUE)
# Close the backend.
context$stop()
Run the code above in your browser using DataLab