Node.js "node-cron" not running on Google app engine - node.js

I have configured this cronjobe using node-cron in my node.js project
const cron = require('node-cron');
cron.schedule('0 0 * * *', () => {
console.log("CRON: Running");
// Do someting
});
and deployed project to Google APP engine, this cron normally runs on my local during testing at 24:00 no issue, but on Google APP engine it is not ...
Project itself normally deployed to server and running no issues (accessible through web) but cornjobe seems did not triggered at 24:00 by app engine server, i'm trying to understand why ?? Seems server was off at moment when no one is using it, or ??

This is because the App Engine instance is not necearily running at the time of the execution. (this happends more with Standard as it can scale down to 0)
Therefore a workaround for have Cronjobs in app engine is to have the schedule of this jobs managed by something else, in this case Google Cloud Scheduler which basically is a scheduler for tasks in app engine.
In This Guide You can see how to create cron job with the cloud Scheduler by the cloud console.

Related

Send a PUT request from all accounts in the database after every 24hours in Production

I have deployed my website, in my website user have to complete 10 orders every day, i want to reset orders at 9am everyday. i am using MERN stack. how to reset orders ? i am thinking of sending put requests that modifies user orders to 0 at 9am everyday.
import schedule from 'node-schedule'
const { currentUser } = useSelector((state) => state.user) //using Redux to fetch current user
schedule.scheduleJob('0 9 * * *', async () => {
try {
await axios.put(`/details/${currentUser._id}`, {
dailyOrders: 0,
})
} catch (err) {
console.log(err)
}
})
I have tried using node-cron but that didn't work well. it will work only if the user is logged in to the account and have opened the site all the time. If he closes site , node cron will not work.
I have deployed my website! and tried using pm2 start myapi
There are potentially multiple options, depending on your architecture and the complexity of your backend servers. Also, I strongly believe that this is a task to be completed on the backend servers rather than the client:
You would need a database query to reset all users' orders
This could be a secure route (e.g accessible only to admins through authentication)
Here are some examples of potential solutions depending on your architecture:
If you are using cloud deployment (e.g AWS) you could set up a lambda function to accomplish this and call it on a given schedule via EventBridge (this is basically a serverless cron job)
If you have only one instance of the backend server running you could set up a cron job on that instance (thinking of node-cron job). However, beware of server downtimes and/or multiple servers running at the same time
In a nutshell, there are many ways to accomplish this (it's not one size fit all situation) however this has to be done on the backend servers

Send scheduled email reports from Angular using node.js

I have set up an Angular project and it is consuming APIs from the NodeJS app.
Angular dashboards have some reports/charts, I will configure a schedule somewhere in DB.
I want to add scheduling functionality so that I will get an automated email containing a graph/chart as an email body.
Can anyone guide me here!
Your scheduling will have to happen out of the NodeJS app since that can be always 'alive' The Angular project is only doing things when you've loaded it in your browser and cannot process that scheduled emails when you don't have it open (unless you were to make it a PWA perhaps, but then still it would be rather convoluted to do it out of Angular).
Do all the processing on the server, including generating and rendering the charts to an email message that you send over SMTP or through a service like Mailgun or Sendgrid.
You can use node-schedule package from npm node-schedule, it will help you to schedule cron jobs whenever you want to send email.
const schedule = require('node-schedule')
const job = schedule.scheduleJob('21 * * * *', function(){
console.log('Send my email.')
})
This will excute this cron at exactly 21min of any hour.
You can go through the npm package for more scheduling details.

How do I run cron/scheduled task in Nextjs 9?

I'm building an app with Nextjs and I'm using pages/api directory for my api endpoints. The server entry/root is hidden for me. How do I immediately run the scheduled task with node-cron when my app is deployed then?
I had the same problem. What you can do are scheduled tasks with the node-cron library. You have to put your task which you want to schedule in your next.config.js file like so:
/** #type {import('next').NextConfig} */
const cron = require('node-cron');
cron.schedule('* * * * *', function () {
console.log('Say scheduled hello')
});
const nextConfig = {
reactStrictMode: true,
}
module.exports = nextConfig
It is recommended that you keep the next.config.js pretty simple as stated here: https://github.com/vercel/next.js/issues/5318#issuecomment-540629772
So if using a custom server inside next.js is not recommended either, the best solution would be to use a third party or boot up a second server
You can use their Custom Server hook to include your task scheduling logic during the server initialization. But keep in mind that this is not recommended:
Before deciding to use a custom server please keep in mind that it should only be used when the integrated router of Next.js can't meet your app requirements. A custom server will remove important performance optimizations, like serverless functions and Automatic Static Optimization.

heroku node.js scheduler is not working

I am trying to schedule a task after 10 minutes in node.js heroku. I have created a file worker.js in program main directory. In worker.js I have just called the controller function that I want to schedule like this :
const reports = require('./app/controllers/reports');
reports.sendEmail();
sendEmail function use to send emails. in Heroku scheduler I have add worker.js as :
but my scheduler is not working. What I am missing in my configuration?
Edit your Heroku Scheduler dashboard, and type node worker.js for the command to be executed.

node-cron does not work properly?

I deployed an app on Heroku: myapp
and I wrote some cron code in it:
var time = require('time');
var CronJob = require('cron').CronJob;
var job = new CronJob({
cronTime: '00 45 12 * * *',
onTick: clearReserve,
start: true,
timeZone: 'Asia/Shanghai'
});
My purpose is call the function named 'clearReserve' everyday in the specific time.
but it only work in the first day I upload my code to heroku, and never do this cron job again.
PS: this "clearReserve" function will manipulate my database, I use MongoLab URI which I created in MongoLab, not the Heroku add-on;
Your cron job is never ran again because Heroku dyno went to sleep. https://devcenter.heroku.com/articles/dynos#dyno-sleeping
In order to have your cron jobs executed you need to keep Heroku app awake 24/7. To make sure your Heroku app does not go to sleep, install the NewRelic Heroku Addon you can set up availability monitoring. You provide a URL which NewRelic pings every 30 seconds, therefore keeping your app awake. The intended purpose of this feature is to alert you if your site goes down for business and performance reasons, but it has the added benefit of preventing your app from idling.
Hope it helps!

Resources