How to trigger cron Job from Dot Net Core API/ C# Application?

2.6k Views Asked by At

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.

1

There are 1 best solutions below

0
On

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.