I'm using Expressjs
At /routes/index.js i have:
app.group('/test', test => {
const testHandler = new testHandler();
test.get('/test-action', testHandler.testAction.bind(testHandler));
});
At /test/handler.js i have
export class testHandler {
constructor() {
}
/**
* #param req
* #param res
* #param next
* #returns {*}
*/
async testAction(req, res, next) {
// todo code here
}
}
I want to create a cronjob to run that route ( for example localhost:3000/test/test-action ) twice an hour.
With PHP i can do it by * */2 * * * php /path_to_webroot/index.php param1 param2
Is there a similar way to do it with Nodejs?
You can use node-cron. It uses similar syntax as you are using in php.
# min hour mday month wday command
*/15 * * * * some-command
to schedule some-command to run every 15 minutes, node-cron would use a similar syntax to specify the time to run:
'0 */15 * * * *'
Well, you need to define your express routes normally. Then inside your cron function you would make a request to that express route you have defined.
request('http://localhost:3000/test/test-action', function(error, response, body) {
if (!error && response.statusCode == 200) {
console.log('im ok')
// console.log(body)
}
})
You can use `request inside your corn job. This way your API will get called every specific time.
Related
How can I execute this with different timings? Please help on this. Thanks in Advance...
const Cron = require('node-cron');
const Cron2 = require('node-cron');
var TaskOne = Cron.schedule('*/10 * * * *', async() => {
//first job implemented here and its working fine
function1();
});
var TaskTwo = Cron2.schedule('*/11 * * * *', async() => {
// Second job implemented here....
//Why this block is not getting executed???????????????????????
function2();
});
How can I execute this with different timings? TaskTwo is not getting executed. Debugger not goes into TaskTwo. Please help on this. Thanks in Advance...
if node-cron is not the only prefrence for you then you can use https://github.com/agenda/agenda
There's no need to require the same package twice, so you should remove Cron2 on the second line. Thus the line var TaskTwo = Cron2.schedule('*/11 * * * *', async() => { should be changed to:
var TaskTwo = Cron.schedule('*/11 * * * *', async() => {
As for why the second schedule is not working, it might be because you didn't start() the schedule, as shown in https://github.com/node-cron/node-cron#start. So adding the code below at the end of your script might trigger both cron to run:
TaskOne.start();
TaskTwo.start();
I am using Suitescript 2.0. There I am trying to reschedule a script for a particular type of error.
I got the below code which can be used to rescheduled the script immediately.
var scriptTask = task.create({
taskType: task.TaskType.MAP_REDUCE
});
scriptTask.scriptId = 'customscript_id';
scriptTask.deploymentId = 'customdeploy_id';
var scriptTaskId = scriptTask.submit();
But I am mainly looking for some option to run it after a certain time like after an hour.
Is it possible to achieve by passing any kind of parameter to the above task?
Any other alternative approach would also helpful.
I had a similar issue, I needed to delay my schedule a certain time in your case a map/reduce script which should be the same.
I fixed it with this approach.
Here is sample code with the approach.
/**
#NApiVersion 2.x
#NScriptType ScheduledScript
#NModuleScope SameAccount
*/
define(['N/file', 'N/record', 'N/render', 'N/runtime', 'N/search', 'N/ui/serverWidget', 'N/format', 'N/task', 'N/log'],
function(file, record, render, runtime, search, serverWidget, format, task, log) {
/**
* Definition of the Scheduled script trigger point.
*
* #param {Object} scriptContext
* #param {string} scriptContext.type - The context in which the script is executed. It is one of the values from the scriptContext.InvocationType enum.
* #Since 2015.2
*/
function execute(scriptContext) {
wait(20000); // it waits 20 sec
//whatever you want to do
}
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
return {
execute: execute
};
});
I need to call a function every given period of time on a route for example my function:
function hello(){
console.log("Hi")
}
app.post("/", (req,res) => {
res.send("Hi")
hello()
}
Well, I didn't put all the code in my application, just the part that matters, I need to call the hello function every 5 seconds. I need to use this method of calling a given function every given period, in my application.
you can use node-schedule !
for example: Execute a cron job every 5 Minutes = */5 * * * *
var schedule = require('node-schedule');
var j = schedule.scheduleJob('*/5 * * * *', function(){
console.log('The answer to life, the universe, and everything!');
});
Another solution:
setInterval
setInterval(() => {
// do something every 5 seconds
}, 5000);
I have built a script that looks at fields within a saved search to process, when the script processes each line of the saved search . The script has to process a lot of lines of data and I'm running into issue where I get an SSS Usage Limit exceeded message just due to the nature of the amount of information that I'm processing. Therefore I'm wondering if on each run of the script if I can limit the amount of orders processed and then consecutively run the script until there aren't any more records that need to be processed
Previously I have just restricted the number of records that the script processes at a time and then just manually trigger the script until there aren't anymore lines left to process. I see that you can trigger the script to run every 15 minutes or so but would like it to run each day and then run in a 15 minute cadence after that until the saved search has been exhausted. Then the script would be triggered to run again the following day etc for every 15 min until all records are processed. From research don't know if this type of scheduling is possible.
code itself is working the scheduling of it is what I need guidance on
The other alternative (and one that I've used successfully) is to exit the scheduled script whent the usage reaches a certain point, but before you exit, trigger the scheduled script again. I've used this successfully to process thousands of records (such as mass deletions).
/**
* #NApiVersion 2.x
* #NScriptType ScheduledScript
* #NModuleScope SameAccount
*/
define(['N/record', 'N/runtime', 'N/search', 'N/task'],
/**
* #param {record} record
* #param {search} search
*/
function(record, runtime, search, task) {
const governanceCap = 9950;
function getAllResults(s) {
var results = s.run();
var searchResults = [];
var searchid = 0;
do {
var resultslice = results.getRange({start:searchid,end:searchid+1000});
resultslice.forEach(function(slice) {
searchResults.push(slice);
searchid++;
}
);
} while (resultslice.length >=1000);
return searchResults;
}
/**
* Definition of the Scheduled script trigger point.
*
* #param {Object} scriptContext
* #param {string} scriptContext.type - The context in which the script is executed. It is one of the values from the scriptContext.InvocationType enum.
* #Since 2015.2
*/
function execute(scriptContext) {
function rescheduleCurrentScript() {
var scheduledScriptTask = task.create({
taskType: task.TaskType.SCHEDULED_SCRIPT
});
scheduledScriptTask.scriptId = runtime.getCurrentScript().id;
scheduledScriptTask.deploymentId = runtime.getCurrentScript().deploymentId;
return scheduledScriptTask.submit();
}
try {
var script = runtime.getCurrentScript();
// GET YOUR SEARCH HERE
var mySearch = getAllResults(
search.create({
type: "transaction",
filters:
[
["mainline","is","T"],
],
columns:
[
"name",
"tranid",
"type",
search.createColumn({
name:"datecreated",
sort: search.Sort.DESC
}),
]
})
);
var recCount = mySearch.length;
for (each in mySearch) {
try {
record.delete({
type: transSearch[each].getValue({name:'type'}),
id: transSearch[each].id
});
} catch (err) {log.error(err.name,err.message) }
var govPointsUsed = 10000-script.getRemainingUsage();
script.percentComplete = (govPointsUsed/governanceCap*100).toFixed(1);
if (govPointsUsed >= governanceCap) {
var taskId = rescheduleCurrentScript();
log.audit('Rescheduling status: ','Task ID:' + taskId);
return;
}
}
} catch (err) { log.error(err.name,err.message + '; Stack: '+err.stack ) };
}
return {
execute: execute
};
});
Worked like a charm!!
I would encourage you to use a Map/Reduce script. That is the correct script type to use when dealing with a lot of data and can handle governance issues much better.
I had this problem some time ago. The map/reduce script can be the solution if you run 2.0 scripts. In my case, I had 'legacy' scripts in versions 1.X and 2.X. And all of them throw from time to time 'SSS_TIME_LIMIT_EXCEEDED'.
My solution :)
I created a script, kind of 'listener'. I removed link to the script because the rep. is not active anymore
// *add the script listener
// [it can be used for both script versions 1.X and 2.X]
/** you have to calculate the 'process usage' by 1 loop cycle.
use script.getRemainingUsage() */
var recallValue = 200;
var stopValue = 200;
var recallIsRequired = true;// use false to stop the script without recall
var script = setScriptListener(recallValue, stopValue, recallIsRequired);
for (var data in data_contaniner){
if(script.canContinue()){
//run you processing
// !important : mark the data as 'processed'.
//otherwise you will have a lot of duplicates after script recall
}else{
//stop the loop
break;
}
}
I am working on a fairly large project coming up, and I am (slowly) finding the ins and outs with requireJS. I can say I love it (the concept) and doubt I'll ever go back to "the old way." That said, I'd like to develop good habitats from the start.
I have a main module called application.js
'use strict';
/**
* Primary application module.
*
* #param {function} jquery | jQuery library. http://jquery.com/
* #returns {object}
*
*/
define([
'jquery'
], function (jquery) {
var Application = {
/**
* Initialization method.
*
* #returns {void}
*
*/
initalize: function () {
// Start doing stuff...
}
};
return Application;
});
So far so good.
What I' curious about, is when I start adding more and more modules. Let's say at some point I have a "contact us" form or some other module that doesn't necessarily need loaded at start up, but will need to be available on page "x".
Would I load it in the list of initial dependencies like this:
'use strict';
/**
* Primary application module.
*
* #param {function} jquery | jQuery library. http://jquery.com/
* #param {object} moduleone | ModuleOne
* #returns {object}
*
*/
define([
'jquery'
'moduleone'
], function (jquery, ModuleOne) {
var Application = {
/**
* Initialization method.
*
* #returns {void}
*
*/
initalize: function () {
// Start doing stuff...
if ($('#moduleOneThing').length) {
// Do stuff with ModuleOne...
}
}
};
return Application;
});
Or is it better to set another define/require block like this:
'use strict';
/**
* Primary application module.
*
* #param {function} jquery | jQuery library. http://jquery.com/
* #param {object} moduleone | ModuleOne
* #returns {object}
*
*/
define([
'jquery'
], function (jquery) {
var Application = {
/**
* Initialization method.
*
* #returns {void}
*
*/
initalize: function () {
// Start doing stuff...
if ($('#moduleOneThing').length) {
require(['moduleone'], function (ModuleOne) {
// Do stuff with Module One...
});
}
}
};
return Application;
});
Or, perhaps I'm way off on everything. In any case I would like to learn the "correct" way from the start in hopes to not have to break bad habits down the road. This is an extremely simple example, but the complexity will grow quickly and I am hopeful to set things up correctly to avoid a pile of steaming garbage in the next few weeks.
Thank you for your time!