注册免广告
您需要 登录 才可以下载或查看,没有账号?立即注册
×
本帖最后由 HelloWorld 于 2025-9-7 18:01 编辑
Azure 提供免费的 Web App 可以运行各种后端:https://shuzijumin.com/thread-7735-1-1.html
但是这个免费版,20 分钟没访问会休眠,下次唤醒要等很久,导致网页打开以为网站挂了
因此想到用免费的 Azure Function App,定时 19 分钟访问一下 Web App 的网址,这样就可以保活了
1. 进 Azure 门户 → “Create a resource” → Function App,套餐方选 Consumption 而不是 Flex Consumption
2. Runtime stack 选 Node.js,Operating System 选 Windows,然后创建
3. 进入你刚建好的 Function App → Create → 模板选 Timer trigger,Schedule 填: 0 */19 * * * * (表示每小时的 0、19、38 分触发)
4. 接下去放入如下代码:- // index.js (Node.js on Azure Functions - Timer trigger)
- const https = require('https');
- const http = require('http');
- module.exports = async function (context, myTimer) {
- context.log('TimerTrigger1 function started');
- // 添加计时器信息日志
- if (myTimer.IsPastDue) {
- context.log('Timer function is running late!');
- }
- const url = "https://xxxxxx.azurewebsites.net";
- if (!url) {
- context.log('PING_URL env not set. Skipping.');
- return;
- }
- context.log(`Pinging: ${url}`);
- try {
- await new Promise((resolve, reject) => {
- const client = url.startsWith('https') ? https : http;
- const req = client.get(url, (res) => {
- context.log(`Ping successful - Status: ${res.statusCode}`);
- res.resume(); // 丢弃响应体,尽快释放连接
- resolve();
- });
- // 设置请求超时(30秒)
- req.setTimeout(30000, () => {
- req.destroy();
- context.log.error('Ping failed: Request timeout');
- resolve(); // 不抛错,避免重试风暴
- });
- req.on('error', (err) => {
- context.log.error('Ping failed:', err.message);
- resolve(); // 不抛错,避免重试风暴
- });
- // 确保请求被发送
- req.end();
- });
- context.log('Ping operation completed successfully');
- } catch (error) {
- context.log.error('Unexpected error during ping operation:', error.message);
- }
- context.log('TimerTrigger1 function completed');
- };
复制代码
备注:
Consumption 计划就是最经典的“无服务器”模式,按调用和执行时间计费。每个订阅有 免费额度(100 万次调用 / 月 + 40 万 GB-s / 月),这种“每 19 分钟 ping 一次”的场景,一个月大概 2,160 次,完全在免费额度里。
Flex Consumption 虽然也按使用计费,但定位是高并发、虚拟网络需求的企业场景,没有单独的“免费额度”优惠,适合更复杂的环境 |