有人建议我使用这个包synced-cron
来安排代码的执行。我有以下代码,当时什么都不做。我的概念是,在设置计划时,使用此包创建一个集合,并将所有传递到计划中的数据存储到将来的指定时间,您可以在不同的函数中执行相同的代码,在我的情况下,将插入到一个Posts
集合中,然后该集合将显示在模板上。
TLDR:用户插入数据,用户选择发布日期,synced-cron
将数据与用户选择的日期一起存储在cronHistory
集合中。到达日期时,会将相同的数据插入到Posts
集合中。
我的假设是这是我对编程的部分知识的结果,而没有了解基础知识。因此,如果有人对学习核心概念有任何建议,我也很开放,因为我认为我浪费了很多时间来提问,而这确实是我所缺少的基本概念。
谢谢!提前寻求任何帮助。
这是我的文件夹结构代码。
**client**
/client/posts/post_item.js
Template.postItem.rendered = function(){
var post = {
title: "testTitleTime",
postContent: "timeContentRest"
};
var time = "at 2:30 pm";
Meteor.call('schedulePosts',post,time, function(error, result) {});
};
所以我的理论是数据被传递到服务器上的流星方法 schedulePosts 。我的意图是将它存储在文档所说的集合中,称为
cronHistory
. 尽管我可能完全误解了 cronHistory 是什么。
**lib**
/lib/posts.js
Meteor.methods({
postInsert: function(postAttributes) {
check(Meteor.userId(), String);
check(postAttributes, {
title: String,
postContent: String
});
var user = Meteor.user();
var post = _.extend(postAttributes, {
userId: user._id,
author: user.username,
submitted: new Date()
});
var postId = Posts.insert(post);
return {
_id: postId
};
}
});
我知道如果将正确的属性传递给它,则此代码可以工作,因此我不必担心它,但它需要与其他所有内容一起工作。
**server**
/server/schedule.js
Meteor.methods({
schedulePosts: function (time, post) {
SyncedCron.add({
name: 'Crunch some important numbers for the marketing department',
schedule: function(parser) {
// parser is a later.parse object
return parser.text(time);
},
job: function() {
Meteor.call('postInsert', post, function(error, result) {});
}
});
var MyLogger = function(opts) {
console.log('Message', opts.message);
};
SyncedCron.start();
}
});
我认为这里发生的是运行方法,根据传递的数据初始化计划
post_item.js
,一旦达到该时间,job
就会运行函数并插入post
数据post_item.js
。
更新尝试新代码。
这是订阅所有集合时发布的示例。
{
"_id": "jgx5qWf4RoeG6u7KJ",
"title": "1 20",
"postContent": "See if it w",
"timeToEnable": "2015-06-20T20:20:00.000Z",
"userId": "t4Y9hqYQCG9gxDgnW",
"author": "admin",
"submitted": "2015-05-20T20:19:27.603Z"
}
当我尝试在下面使用它时,当我将它从 更改$lt
为$gt
它返回所有内容时,什么都不会返回,但是,如果我为将来安排一个帖子,它也会输出它。我不确定我可能做错了什么,也许这是我的 timeToEnable 日期的格式?
Meteor.publish('posts', function() {
var selector = {timeToEnable: {$lt: new Date()}};
return Posts.find(selector);
});