How to execute a console application as a parameter


#1

I need to run something like:

exePath = …some executable on the target machine
commandline = String.Format("{0} {1}", exepath, argument);
Hangfire.BackgroundJob.Enqueue(() => commandline);

how to do that ?


#2

This is what I would do:

Define the job as an interface:

interface ICommandLineExecutorJob {
    Task Execute(string commandLine, string[] arguments, PerformContext context, IJobCancellationToken cancellationToken)
}

Implement this interface in the process executing the hangfire jobs:

internal class CommandLineExecutorJobHandler : ICommandLineExecutorJob {
  internal Task Execute(string commandLine, string[] arguments, PerformContext context, IJobCancellationToken cancellationToken) {
     /*  Whatever implementation you have for executing the file
      *  like new Process() or new ProcessStartInfo() or...
      *  Use the cancellationToken to kill the process if needed.   
      *  Use the PerformContext to access things like the JobId or extra data 
      *  attached to the job, or log output from command to the hangfire dashboard
      * through addons like [Hangfire.Console](https://github.com/pieceofsummer/Hangfire.Console)...
      */
  }
}

Schedule your execution:

   Hangfire.BackgroundJob.Enqueue<ICommandLineExecutorJob>(x => x.Execute("git", "log"));

The separation between the job definition (ICommandLineExecutorJob) and job implementation (CommandLineExecutorJobHandler) is very nice if the application scheduling jobs is different from the application executing the jobs. Then you can include the interface in the scheduling app without also having to distribute the implemntation of it.
It requires you to use some IoC container, though, so that Hangfire understands that it needs to use the CommandLineExecutorJobHandler-class for executing ICommandLineExecutorJob.Execute(...).