利用 yajs 云函数,不到 50 行代码实现基金变动提醒

333 天前
 1156909789

第一步 直接新建 fund.ts 编写

import axios from 'axios'
import type { FUNCAPP, FUNCCTX } from '../context'
const ctx: FUNCCTX = _CTX
const app: FUNCAPP = _APP

// 基金代码
const code = '012414'
//企业微信 api
const qyApi = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx'

// http 访问时输出
export const main = async () => {
    const { name, price, ratio } = await getFundData(code)
    return { data: { fund: { name, price, ratio } } }
}

// cron 定时任务执行方法
export const cron = async () => {
    console.log('cron start')
    const { name, price, ratio } = await getFundData(code)
    if (ratio < -0.2 || ratio > 2) {
        await axios.post(qyApi, {
            "msgtype": "text",
            "text": {
                "content": `请注意${name}基金变动`
            }
        })
    }
}

const getFundData = async (code: string) => {
    const str: string = await axios.get(`http://hqf.stock.sohu.com/kfund/${code}_6.up`)
        .then(res => res.data)
    //剔除 fortune_hq( );
    const jsonStr = str.substring(11).slice(0, -3).replace(/\'/g, '"')
    const data = JSON.parse(jsonStr)
    const name = data.price[1]
    const price = parseFloat(data.price[2])
    const ratio = parseFloat(data.price[3])
    const result = { name, price, ratio }
    // 可以 db 保存起来
    // await ctx.redis.setex(dayjs().format('YYYY-MM-DD') + '-' + code, 7200, JSON.stringify(result))
    // await ctx.knex('fund').insert(result) //先得创建表
    return result
}

第二步:修改配置文件的 token 和 cron

exports.config = {
    default: {
        project: "test",
        token: "123456",
        url: "http://127.0.0.1:3000",
        secret: {},
        crons: [
            { label: 'fund', name: 'fund', cron: '0 40 14 * * *' }
        ]
    }
}

第三步:部署

yajs -n fund
yajs --cron

完成搞定,撒花

相关代码已上传 github

https://github.com/mtnbgx/yajs-example

https://github.com/mtnbgx/yajs

Yajs 是一个自运行的云函数开源框架,运行内存小于 100m ,适合各种 serverless 、云开发退坑后替代

2242 次点击
所在节点    分享创造
10 条回复
kkk9
333 天前
看是推广框架放心了,😅
8863824
333 天前
还行,我目前也有类似需求,不过都是直接用 pm2 管理的。
不过要是能直接提供云服务,然后 git 一提交能自动跑就爽了
gongquanlin
333 天前
@8863824 云函数、laf.dev 、vercel 都满足你的需求呀
1156909789
333 天前
@8863824 可以的,但是需要自己配置一下 Jenkins 之类的工具,代码提交后运行 yajs -p 发布全部函数
1156909789
333 天前
@gongquanlin 提供一个轻量自托管的解决方案而已,看需求选择咯
whileFalse
333 天前
个人自建云函数是闲得慌么,用 cron 就完了
8863824
333 天前
@gongquanlin 你说的这种是托管网站的吧。我想要的偏这种定时任务一点,最好是可以有个监控面板
wzblog
333 天前
可以的,还会继续完善项目吗?已 star
1156909789
333 天前
@wzblog 会的,我自己也要用
gongquanlin
333 天前
@8863824 那就是青龙面板了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/985334

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX