How can we run the node-cron job in every 12 hours interval? - node.js

I want to schedule the email after every 12 hrs , For that I have used node-cron.
I have used the following code but its not giving me actual result, so please help me to resolve this issue,
var job = new CronJob('0 0 */12 * * *', function(){
//email send code ..
});

Looking at the documentation the code should look like this:
var cron = require('node-cron');
cron.schedule('0 0 */12 * * *', function(){
console.log('running a task every twelve hours');
});
Note: You need to have the app running all the time or the cron won't be executed.
And If you print the crone time on console the we wil get like as follows :
cronTime: {
source: '0 0 */12 * * *',
zone: 'America/Los_Angeles',
second: {
'0': true
},
minute: {
'0': true
},
hour: {
'0': true,
'12': true
},
dayOfMonth: {
'1': true,
'2': true,
'3': true,
'4': true,
'5': true,
'6': true,
'7': true,
'8': true,
'9': true,
'10': true,
'11': true,
'12': true,
'13': true,
'14': true,
'15': true,
'16': true,
'17': true,
'18': true,
'19': true,
'20': true,
'21': true,
'22': true,
'23': true,
'24': true,
'25': true,
'26': true,
'27': true,
'28': true,
'29': true,
'30': true,
'31': true
},
month: {
'0': true,
'1': true,
'2': true,
'3': true,
'4': true,
'5': true,
'6': true,
'7': true,
'8': true,
'9': true,
'10': true,
'11': true
},
dayOfWeek: {
'0': true,
'1': true,
'2': true,
'3': true,
'4': true,
'5': true,
'6': true
}
},

You can try this module https://www.npmjs.com/package/node-schedule
var schedule = require('node-schedule');
var rule = new schedule.RecurrenceRule();
var j = schedule.scheduleJob('1 * * * * *', function(){
console.log('Will run after every mint');
});
var rule = new schedule.RecurrenceRule();
rule.second=1;
var j = schedule.scheduleJob(rule, function(){
console.log('this will run after every one seocnd ');
});

Try this for 12 hours interval ...
var job = new CronJob('0 0 12 * * *', function(){
//email send code ..
});
0 --> for seconds
0 --> for minutes
12--> for 12 hours interval

Related

agenda scheduling defaulting nextRunAt to next year

I am trying to schedule jobs usign the agenda library. I've done this:
await this.agenda.start()
this.agenda.define(scheduler.id, { lockLifetime: 10000 }, (job, done) => {
console.log('Hello world!')
//some logic using values on job variable
done()
})
const result = await this.agenda.every(scheduler.cron, scheduler.id, scheduler, { startDate: new Date() })
await this.agenda.start() //i added start here too just in case
console.log(result)
That last console.log shows that the job was created successfully and it even saves on database, but the nextRunAt defaults to 1st of january 2022 for some reason (as seen on the full object below). I tried adding the startDate on the every() call but it still shows 2022 and i have no idea why. No matter what cron i send it still doesnt work. The only param i send to Agenda constructor is the database, nothing about when to start.
Thanks!
Job {
agenda: Agenda {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
_findAndLockNextJob: [Function: findAndLockNextJob],
_name: undefined,
_processEvery: 5000,
_defaultConcurrency: 5,
_maxConcurrency: 20,
_defaultLockLimit: 0,
_lockLimit: 0,
_definitions: { '61af764f8f26fb369c76b571': [Object] },
_runningJobs: [],
_lockedJobs: [],
_jobQueue: JobProcessingQueue { _queue: [] },
_defaultLockLifetime: 600000,
_sort: { nextRunAt: 1, priority: -1 },
_indices: { name: 1, nextRunAt: 1, priority: -1, lockedAt: 1, disabled: 1 },
_isLockingOnTheFly: false,
_isJobQueueFilling: Map(0) {},
_jobsToLock: [],
_ready: Promise { undefined },
_db: MongoClient {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
s: [Object],
topology: [Topology],
[Symbol(kCapture)]: false,
[Symbol(options)]: [Object: null prototype]
},
_mdb: Db { s: [Object] },
_collection: Collection { s: [Object] },
_processInterval: Timeout {
_idleTimeout: 5000,
_idlePrev: [TimersList],
_idleNext: [TimersList],
_idleStart: 28573,
_onTimeout: [Function: bound processJobs],
_timerArgs: undefined,
_repeat: 5000,
_destroyed: false,
[Symbol(refed)]: true,
[Symbol(kHasPrimitive)]: false,
[Symbol(asyncId)]: 221,
[Symbol(triggerId)]: 0
},
[Symbol(kCapture)]: false
},
attrs: {
name: '61af764f8f26fb369c76b571',
data: {
//stuff that i use here
},
priority: 0,
type: 'single',
nextRunAt: 2022-01-01T03:00:00.000Z, //next run at 2022
repeatInterval: '* * * 1 *',
repeatTimezone: null,
startDate: 2021-12-07T14:57:19.394Z,
endDate: null,
skipDays: null,
_id: new ObjectId("61af764fcb12102f92e637dc")
}
}
Using crontab i noticed that the problem was my cron job that was going to run on the 1st day of the next month, nothing to do with the lib. Now with a correct cron its working as intended

npm pdfjs creates corrupted PDF files

I am trying to create PDF files with the npm library pdfjs https://www.npmjs.com/package/pdfjs . Once all the elements (paragraphs) of the file are append to the doc I create the file, but when opening it I have a message it says is corrupted.
When I use doc.end() to finish the document, says there is no function. So I used a promise and tried to use later on the information. But even when I get an object with all the data, I can't manage to make the .pdf file not corrupted.
This is the code I'm using:
const pdf = require('pdfjs')
const fs = require('fs')
function createPDF(data, options){
return new Promise((resolve, reject) => {
var doc = new pdf.Document({ font: require('pdfjs/font/Helvetica') });
var header = doc.header().table({ widths: [null, null], paddingBottom: 1*pdf.cm }).row()
header.cell().image('/images/logo.png', { height: 2*pdf.cm })
header.cell().text({ textAlign: 'right' })
.add('Example.')
.add('https://www.example.com', {
link: 'https://www.example.com',
underline: true,
color: 0x569cd6
})
doc.footer()
.pageNumber(async function(curr, total) { return curr + ' / ' + total }, { textAlign: 'center' });
resolve(doc)
});
}
var doc = createPDF();
doc.then(async (data) => {
data.pipe(fs.createWriteStream('output.pdf'))
console.log(data);
await data.end();
})
Log Data:
Document {
_readableState:
ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes:
WriteStream {
_writableState: [Object],
writable: true,
domain: null,
_events: [Object],
_eventsCount: 5,
_maxListeners: undefined,
path: 'output.pdf',
fd: null,
flags: 'w',
mode: 438,
start: undefined,
autoClose: true,
pos: undefined,
bytesWritten: 0 },
pipesCount: 1,
flowing: true,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: true,
paused: false,
emitClose: true,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events:
{ read: { [Function: bound onceWrapper] listener: [Function] },
end: { [Function: bound onceWrapper] listener: [Function: onend] },
data: [Function: ondata] },
_eventsCount: 3,
_maxListeners: undefined,
version: '1.6',
info: { id: '34d7f55c-5961-4caf-9814-1902b98bee3c' },
width: 595.296,
height: 841.896,
_nextObjectId: 4,
_xref: PDFXref { objects: [], trailer: null },
_reading: false,
_length: 0,
_pending:
[ [Function],
[ [Function], [Array], [Array], [Function] ],
[Function],
[Function],
[Function],
[Function],
current: Promise { <pending> } ],
defaultFont:
AFMFont {
_data:
{ fontName: 'Helvetica',
fullName: 'Helvetica',
familyName: 'Helvetica',
italicAngle: 0,
characterSet: 'ExtendedRoman',
fontBBox: [Array],
underlinePosition: -100,
underlineThickness: 50,
capHeight: 718,
xHeight: 523,
ascender: 718,
descender: -207,
kerning: [Object],
widths: [Array] },
lineGap: 231,
parent: [Circular] },
defaultFontSize: 11,
defaultColor: [ 0, 0, 0 ],
defaultLineHeight: 1.15,
_fonts: { '/F1': { f: [Object], o: [Object] } },
_xobjects: {},
_pageFonts: {},
_annotations: [],
_aliases: AliasGenerator { nextId: { F: 2 }, blocked: Set {} },
_mapping: WeakMap {},
_currentContent: null,
_contents: [],
_contentObjCreator: null,
_finalize: [],
_template: null,
_footer: null,
_header: null,
paddingTop: 20,
paddingBottom: 20,
paddingLeft: 20,
paddingRight: 20,
_cursor:
Cursor {
width: 555.296,
height: 801.896,
x: 20,
startX: 20,
y: 821.896,
startY: 821.896,
_bottom: 20,
bottomOffset: 0 },
_pages: [ toString: [Function] ],
_pagesObj:
PDFObject {
id: 2,
rev: 0,
properties: PDFDictionary { dictionary: [Object] },
reference: PDFReference { object: [Getter] },
content: 'stream\n!!!Djz!WW3#D/OH9;Fa%r=BSfM#MB(Z!#knQ!$hOd#:O#tzzzz!!!!"zz!!)`D!!*\'"!!(J"z\'&psr`WC#h?J?20S8TbAzzzzzzz!!!!1A7]gl!!!
$f!!!"E#TZc:!!!&8!!!!5#T65m!!!&L!!!95B2hbr!!!&L!!!95E`>q(!!!&L!!!95A8Pjf!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!!+_F(o80z6W-l+A7]glz
!!!!N;IsHOEb0,uAKY#fATqj+B-9Q[DIdI\'Bl#l3Bl5%b77/1U0f_-M/M\\n4zzzzzzzzzzzzzzzzzzzz=BSfMz!!)`D!!*\'"!!(J"FCf]=z6Z6phEbT0"F<F.mFCfK1#<?4%DII
?(6Z6dZEZd_fDKB`:FD5l7/0H]%0KB+5F(R3`z!!*Kr!!!2[s8V[;!!!7g!!)tYs8Vtis8W%l!!!,U!!\'fW~>\nendstream\n' },
_currentColorSpace: '/CS1',
_doc: [Circular],
_parent: [Circular],
_ended: false,
_current:
Footer {
_doc: [Circular],
_parent: [Circular],
_cursor:
ClonedCursor {
width: 555.296,
height: 801.896,
bottomOffset: 0,
startX: 20,
startY: 821.896,
_root: [Object] },
_ended: false,
_current: null,
_pending:
[ [Function],
[Array],
[Function],
[Function],
[Function],
[Function],
current: [Object] ],
_objects: [],
_pageNumbers: [] } }
It looks like the content is there but can't manage to get it. And whe await data.end(); is run, it show the next error log show:
TypeError: Invalid value used as weak map key TypeError: Invalid value used as weak map key
at WeakMap.set (native)
at Document._useXObject (/home/developer1/Projects/bfreit_website/node_modules/pdfjs/lib/document.js:255:21)
at module.exports (/home/developer1/Projects/bfreit_website/node_modules/pdfjs/lib/image/render.js:16:23)
at _pending.push (/home/developer1/Projects/bfreit_website/node_modules/pdfjs/lib/fragment.js:143:30)
at Document._next (/home/developer1/Projects/bfreit_website/node_modules/pdfjs/lib/document.js:169:36)
at _pending.current.next.then (/home/developer1/Projects/bfreit_website/node_modules/pdfjs/lib/document.js:172:19)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
The expected output is a correct .pdf file. But even when my output is a .pdf file, it is corrupted.
Unable to open document “file:///home/developer1/Projects/pdf/output.pdf”.
Error when trying to open the file:
PDF document is damaged
If you can help me either solving this, or with a library of your knowledge that it works will be bomb.
I could not found a solution for the pdfjs library. But I found a library that worked better in my project. It is really easy to work with.
Short Example:
const pdf = require('pdfkit');
const fs = require('fs');
const doc = new pdf();
doc.pipe(fs.createWriteStream('/my/path'));
doc.fontSize(10).text('Fontsize 10')
doc
.fontSize(18)
.text('Font Size 18 aligned right', {align: 'right'});
doc.moveDown();
doc.fontSize(14).text('Font size 14 aligned center',{align:'center' })
doc.end();

jqGrid export to excel issue when loadonce option is setted to false

I have an ASP.net MVC solution and use jqGrid in it. To have a better performance I use loadonce: false as an option and it should be in this way, unfortunately It seems to be not supported by jqGrid because I cannot find any sign of that throughout my search.
$(document).ready(function () {
$("#jqGrid").jqGrid(
{
url: "/Student/GetStudents",
mtype: "GET",
datatype: "json",
contentType: "application/json; charset-utf-8",
jsonReader: {
root: "rows",
id: "StudentId",
repeatitems: false
},
colNames: ['StudentId', 'FirstName', 'LastName'],
colModel: [
{ label: 'StudentId', name: 'Id', key: true, width: 75 },
{ label: 'FirstName', name: 'FirstName', width: 150 },
{ label: 'LastName', name: 'LastName', width: 150 },
],
viewrecords: true,
loadonce: false,
width: '100%',
height: 'auto',
rowNum: 20,
rowList: [20, 30, 50],
sortable: true,
sortname: 'Id',
pager: "#jqGridPager",
autoencode: true,
scroll: false,
pgbuttons: true,
autowidth: true,
shrinkToFit: false,
forceFit: false,
gridview: false,
height: '100%',
scrollrows: true,
page: 1,
//pagerpos: 'center',
toppager: true,
recordpos: 'right',
multiselect: true,
multiboxonly: true,
direction: 'rtl',
ignoreCase: true,
caption: "",
rownumbers: true
});
$('#jqGrid').jqGrid('navGrid', '#jqGridPager', {
search: true,
searchtext: "Search",
edit: false,
add: false,
del: false,
excel: true,
refresh: false,
}, {}, {}, {}, {
closeOnEscape: true,
closeAfterSearch: true,
ignoreCase: true,
multipleSearch: false,
multipleGroup: false,
showQuery: false,
sopt: ['cn', 'eq', 'ne'],
defaultSearch: 'cn'
})
$('#jqGrid').jqGrid('navButtonAdd', '#jqGridPager', {
caption: "Export to Excel",
//buttonicon: "ui-icon-disk",
buttonicon: "ui-icon-folder-open",
onClickButton: function () {
exportToExcel();
},
});
});
function exportToExcel(data, e) {
exportExcelFile(data);
}
function exportExcelFile() {
debugger;
var data = $('#jqGrid')[0].addLocalData(true);
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
frame1.document.open("txt/html", "replace");
frame1.document.write(setTableOfData(data));
frame1.document.close();
frame1.focus();
sa = frame1.document.execCommand("SaveAs", true, "text.xls");
} else
$('#jqGrid').jqGrid('exportToExcel', { fileName: "exportedExcel.xls", navigator: true });
}
function setTableOfData(data) {
var htmlString = '<table>';
var header = '<tr><td>StudentId</td><td>FirstName</td><td>LastName</td></tr>';
htmlString += header;
for (var i = 0; i < data.length; i++) {
var tag = '<tr><td>' + data[i].Id + '</td><td>' + data[i].FirstName + '</td><td>' + data[i].LastName + '</td></tr>';
htmlString += tag;
}
htmlString += '</table>';
return htmlString;
}
Finally, I forced to post all the filtering and other settings of the grid to the server and return a link to the client. Then with the given link I became able to download the excel file.
Info: you can not download a file with post(ajax) request.

Using Sequelize with ES6 Promises?

I'm using Sequelize to connect to a Postgres database. I have this code:
return Promise.resolve()
.then(() => {
console.log('checkpoint #1');
const temp = connectors.IM.create(args);
return temp;
})
.then((x) => console.log(x))
.then((args) =>{
console.log(args);
args = Array.from(args);
console.log('checkpoint #2');
const temp = connectors.IM.findAll({ where: args }).then((res) => res.map((item) => item.dataValues))
return temp;
}
)
.then(comment => {
return comment;
})
.catch((err)=>{console.log(err);});
In the first .then block at checkpoint #1, the new record is successfully added to the Postgres database. In the console.log(x) in the next then block, this gets logged to the console:
{ dataValues:
{ id: 21,
fromID: '1',
toID: '2',
msgText: 'Test from GraphIQL',
updatedAt: Wed Oct 12 2016 09:52:05 GMT-0700 (PDT),
createdAt: Wed Oct 12 2016 09:52:05 GMT-0700 (PDT) },
_previousDataValues:
{ fromID: '1',
toID: '2',
msgText: 'Test from GraphIQL',
id: 21,
createdAt: Wed Oct 12 2016 09:52:05 GMT-0700 (PDT),
updatedAt: Wed Oct 12 2016 09:52:05 GMT-0700 (PDT) },
_changed:
{ fromID: false,
toID: false,
msgText: false,
id: false,
createdAt: false,
updatedAt: false },
'$modelOptions':
{ timestamps: true,
instanceMethods: {},
classMethods: {},
validate: {},
freezeTableName: false,
underscored: false,
underscoredAll: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: [],
hooks: {},
indexes: [],
name: { plural: 'IMs', singular: 'IM' },
omitNul: false,
sequelize:
{ options: [Object],
config: [Object],
dialect: [Object],
models: [Object],
modelManager: [Object],
connectionManager: [Object],
importCache: {},
test: [Object],
queryInterface: [Object] },
uniqueKeys: {},
hasPrimaryKeys: true },
'$options':
{ isNewRecord: true,
'$schema': null,
'$schemaDelimiter': '',
attributes: undefined,
include: undefined,
raw: undefined,
silent: undefined },
hasPrimaryKeys: true,
__eagerlyLoadedAssociations: [],
isNewRecord: false }
In the .then((args) => code block at checkpoint #2, args comes in as undefined.
How do I get args to contain an array of results from checkpoint #1?
.then((x) => console.log(x))
.then((args) =>{
is like doing
.then((x) => {
console.log(x);
return undefined;
})
.then((args) =>{
because console.log returns undefined. That means the undefined value will be what gets passed to the next .then.
The easiest approach would be to explicitly
.then((x) => {
console.log(x);
return x;
})
or in a shorter version using the comma operator
.then((x) => (console.log(x), x))

moment returns wrong value

I'm parsing a date using momentjs:
var startDate = moment.utc('2016-02-20T07:00:00.000Z')
If I'm writing startDate.toISOString() to the console, I get this:
2016-02-19T21:00:00.000Z
The startDate object looks like this:
{ [Number: 1455915600000]
_isAMomentObject: true,
_i: '2016-02-20T07:00:00.000Z',
_f: 'YYYY-MM-DDTHH:mm:ss.SSSSZ',
_tzm: -0,
_isUTC: true,
_pf:
{ empty: false,
unusedTokens: [],
unusedInput: [],
overflow: -1,
charsLeftOver: 0,
nullInput: false,
invalidMonth: null,
invalidFormat: false,
userInvalidated: false,
iso: true },
_locale:
Locale {
_ordinalParse: /\d{1,2}(th|st|nd|rd)/,
ordinal: [Function],
_abbr: 'en',
_ordinalParseLenient: /\d{1,2}(th|st|nd|rd)|\d{1,2}/ },
_d: Fri Feb 19 2016 22:00:00 GMT+0100 (CET),
_isValid: true,
_offset: 0 }
Where does this difference result from?

Resources