1

I am having the following use case.

We already have a cron job deployed on a Linux server which runs continuously.

Now we need to trigger this job on-demand/ some button click event/ through API.

For example, we have a screen to get the export data request from the user and once user placed this request, we need to trigger the cron job which will export file and send it to the user by email. Exporting the file is a long-running process that's why we have created a job.

I have one solution that is to use QuartzNet but I do not want to modify or change the job implementation. Is there any way that we can trigger this cron job from C# code?

Any help will be appreciated.

rajk
  • 221
  • 3
  • 19
  • 1
    Cronjob normally means that there's simply an command line application. new Process().start() can be used to start it if you're on the same machine. If you want to start it from remote, you'd have to create an app (e.g. asp core api) that allows you to send http request to trigger the run. Quartz, Hangfire… are "cron managers" itself and would help you if you want to REPLACE you existing cron job. – Christoph Lütjen Nov 07 '18 at 18:29

1 Answers1

0

A cron job is just a bash command. You can simply take the same command that is in your crontab, and call that using something along the lines of:

public static void StartCommand(string cmd)
{
    var escaped = cmd.Replace("\"", "\\\"");

    var process = new Process()
    {
        StartInfo = new ProcessStartInfo
        {
            FileName = "/bin/bash", // or whatever shell you use
            Arguments = $"-c \"{escaped}\"",
            UseShellExecute = false,
            CreateNoWindow = true,
        }
    };
    process.Start();
}

Example call:

SomeClass.StartCommand("exportprocess \"argument\" --example-flag");

Of course depending on your needs you can use process.WaitForExit();, read the standard output, etc.

Marcell Toth
  • 3,433
  • 1
  • 21
  • 36