Run an Azure Function Every 15 minutes - azure

I have an Azure Function whose method looks like this:
[FunctionName("RunTask")]
public static async Task Run([TimerTrigger("0 */15 * * * *")]TimerInfo myTimer, TraceWriter log)
{
log.Info("Running task...");
await Task.CompletedTask;
}
The above method is only a shell to test the timing abilities. I want the function to run every 15 minutes. However, the task seems to only run on the first pass. I'm basing this on what I see in the Azure Portal. In the Azure Portal, I select the RunTask function to view the Logs. This lets me watch the trace logs in real time.
The first log appears correctly. However, I do not see any additional logs written. Instead, I see "No new trace in the past [x] min(s)."
Oddly, if I change the timer from 15 minutes to 5 minutes ([TimerTrigger("0 */15 * * * *")] to [TimerTrigger("0 */5 * * * *")]), it works as expected. Why is that? How do I setup my function to run every 15 minutes?
Please note, I have to use the Microsoft.NET.Sdk.Functions-1.0.24 implementation.
Thank you!

There is no problem with the timer trigger. Your function is triggered every 15 minutes successfully, but the log window is fragile. It sometimes will not show the logs after a few minutes, so when you set the timer from 15 to 5 minutes it shows the logs normally.
For this problem, you can see the logs of your function by following the steps below:
Go to "kudu" of your function app.
Then click "Debug console" --> "CMD" --> "LogFiles" --> "Application" --> "Functions" --> "function", choose your function, click the edit pencil, then you can see the logs.

Related

Vanilla NodeJS Cron Job?

I want to do something in node at, say, midnight each day.
I see a lot of stuff pointing me to node-cron, and I see this article configuring a docker container to execute a script per a crontab
I want to 1. not use any external packages and 2. keep the script being executed inside the server code itself (i.e. I couldn't have the docker container execute some other file on a schedule)
The use case is I want to update a cache on the server every day around midnight, and then, at more frequent intervals, use that cache for various things.
You can use setInterval to run the code every hour and check if it's around midnight
setInterval(() => {
if (new Date().getHours() === 0) {
// do stuff
}
}, 1000 * 60 * 60 * 60)

Repeatable jobs not getting triggered at given cron timing in Bull

I wanted to perform some data processing in parallel using Bull NPM and start processing each job at the given cron Time
const Queue = require("bull"),
/**
* initialize the queue for executing cron jobs
**/
this.workQueue = new Queue(this.queueOptions.name, {
redis: redisConfig
});
this.workQueue.process((job, done) => {
done();
this.processJob(job)
.then(data => {
global.logger.info(`successfully-executed-job ${job.id}`);
})
.catch(error => {
global.logger.error(`JSON.stringify(error)}-in-executing-job-${job.id}`);
});
});
// here I have included Unique JobId
this.workQueue.add({}, {repeat: { cron:"5 * * * *",jobId:Date.now()});
Any suggestions to achieve the same?
The issue is resolved now if you're facing the same issue make sure that you're referring to the correct timezone.
Cheers!!
I also faced this same issue. One thing to note with respect to the above code is that a Queuescheduler instance is not initialized. Ofcourse timezone also plays a crucial role. But without a Queuescheduler instance (which has the same name as the Queue), the jobs doesnt get added into the queue. The Queuescheduler instance acts as a book keeper. Also take care about one more important parameter "limit". If you dont set the limit to 1, then the job which is scheduled at a particular time will get triggered unlimited number of times.
For example: To run a job at german time 22:30 every day the configuration would look like:
repeat: {
cron: '* 30 22 * * *',
offset: datetime.getTimezoneOffset(),
tz: 'Europe/Berlin',
limit: 1
}
Reference: https://docs.bullmq.io/guide/queuescheduler In this above link, the documentation clearly mentions that the queuescheduler instance does the book keeping of the jobs.
In this link - https://docs.bullmq.io/guide/jobs/repeatable, the documentation specifically warns us to ensure that we instantiate a Queuescheduler instance.

Where can I see the next time the function starts?

I have a function in Azure on Python that runs every 12 hours:
{
"scriptFile": "__init__.py",
"bindings": [
{
"name": "mytimer",
"type": "timerTrigger",
"direction": "in",
"schedule": "0 0 */12 * * *"
}
]
}
Is there any way to see when the next launch will be made?
I'm not sure if there is a way to see the trigger time directly, but since your time trigger is every 12 hours, so we can get to know the next trigger time indirectly by the request history in "Monitor" of the function.
In the "Monitor" tag (here in the screenshot above, I deployed a time trigger function triggered every minute), we can see the running history of the function, since we can see the last running time, so we can also know the next trigger time(the last time +12hours).
By the way, if we want to use the monitor, we need to enable application insights when we create the function app.
Hope it would be helpful to your question~
Update:
We can also see the time of next launch in "Live Metrics Stream", shown as below:
click "Monitor" --> "Live app metrics"
we can find the next time in the message in "Sample Telemetry"

Azure Scheduled WebJob Never Finished Status

I have a scheduled web job that runs a function every minute:
[TimerTrigger("00:01:00", RunOnStartup = true)]
Sometimes it hangs and has a "Never Finish" status for a few days. This prevents new schedules for the job to be triggered. The Azure log also didn't record any entries - log was empty for that run.
I wonder if there is a way to tell Azure scheduler to continue with the scheduling if the job has a "Never Finish" status / state? Does setting "UseMonitor = true" do this?
As far as I know, if the scheduled web job processing is taking a long time periodically (or not finishing at all), it must be that every now and then the operations in your job function take a long time or fail. All depends on what your job is actually doing internally. If it is going async in places, the SDK will continue to wait for it to return.
According to this, I suggest you could try to use webjob's TimeoutAttribute.
It easy for functions to be cancelled based on timeout if they're hung.It will show a exception.
If you find the error is too much and you want to alter, I suggest you could use ErrorTrigger, you could refer to this article.
More details, you could refer to below codes.
I used the queue to test it, the result is as same as TimerTrigger webjob.
//Change the function timeout value
[Timeout("00:00:03")]
public static void TimeoutJob(
[QueueTrigger("queue")] string message,
CancellationToken token,
TextWriter log)
{
Console.WriteLine("From function: Received a message: " + message);
Task task = new Task(new Action(() => /*here is your code*/ Thread.Sleep(5000)), token);
// this will cancel the task is the token is CancellationRequested and show the exception the task is cancel
task.Wait();
Console.WriteLine("From function: Cancelled: Yes");
}

nodejs setTimeout not working when called from cron job

I am writing a nodejs program, which needs to upload local sensor information to central database every 15 seconds. since the minimum cron interval is 1 minute, i am calling the the upload routine 4 times like this
function uploadToDatabase() { /* blah blah blah */ }
setTimeout(uploadToDatabase, 1*1000);
setTimeout(uploadToDatabase, 15*1000);
setTimeout(uploadToDatabase, 30*1000);
setTimeout(uploadToDatabase, 45*1000);
this function getting called as intended when i run this in command like like
node uploader.js
but when this is called from cron job this function uploadToDatabase never called?
Any idea why?
You don't need a cron job. Just run it in node and have a loop that executes every 15 seconds.

Resources