我正在按照教程:https://cloud.google.com/solutions/mobile/firebase-app-engine-android-studio
我有一切正常,电子邮件每2分钟发送一次.但是,我现在希望将其扩展为仅在Firebase节点上更改数据时触发发送电子邮件,而不是每2分钟发送一条消息.
测试我替换了cron.xml文件 从:
<?xml version="1.0" encoding="UTF-8"?>
<cronentries>
<cron>
<url>/hello</url>
<description>Send me an email of outstanding items in the morning</description>
<schedule>every 2 minutes</schedule>
</cron>
</cronentries>
至:
<?xml version="1.0" encoding="UTF-8"?>
<cronentries/>
清除计划任务.
但是现在在对Firebase数据库进行更改时,电子邮件永远不会发送….
如何让我的应用引擎服务器“监听”firebase节点,然后实时生成onDataChanged上的操作?
MyServlet类:
public class MyServlet extends HttpServlet {
static Logger Log = Logger.getLogger("com.example.username.myapplication.backend.MyServlet");
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
Log.info("Got cron message, constructing email.");
//Create a new Firebase instance and subscribe on child events.
Firebase firebase = new Firebase("[firebase ref]");
firebase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Build the email message contents using every field from Firebase.
final StringBuilder newItemMessage = new StringBuilder();
newItemMessage.append("This should arrive very closely after changing the data");
//Now Send the email
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
try {
Message msg = new MimeMessage(session);
//Make sure you substitute your project-id in the email From field
msg.setFrom(new InternetAddress("anything@[app-engine].appspotmail.com",
"Todo Nagger"));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress("myEmail@gmail.com", "Recipient"));
msg.setSubject("Feast Email Test");
msg.setText(newItemMessage.toString());
Transport.send(msg);
} catch (MessagingException | UnsupportedEncodingException e) {
Log.warning(e.getMessage());
}
}
public void onCancelled(FirebaseError firebaseError) {
}
});
}
}
解决方法: 您的问题实际上是关于AppEngine以及如何创建自动启动并自动执行某些初始化的Servlet的问题.
您需要保持手动缩放,但请按照此处的步骤操作: https://cloud.google.com/appengine/docs/java/config/appconfig#using_a_load-on-startup_servlet
用于在init()而不是http请求上设置侦听器. 你正在尝试的是绝对可能的,并且已经看到它在其他地方运行. 来源:https://www./content-4-260801.html
|