I want my lambda functions to be called on a schedule on my local machine so that I can easily test them before deploying. Is there any way for this?
This is my function:
sendMonthlyReport:
Type: AWS::Serverless::Function
Properties:
Handler: src.monthlyReport
Runtime: nodejs16.x
Events:
ScheduledEvent:
Type: Schedule
Properties:
Schedule: "cron(* * * * *)"
CodePudding user response:
I would use node-cron to set a scheduler on a node file to run.
npm install --save node-cron
var cron = require('node-cron');
cron.schedule('* * * * *', () => {
console.log('running a task every minute');
});
https://www.npmjs.com/package/node-cron
You can also check for this DigitalOcean tutorial!
CodePudding user response:
If you search for local testing before deployment of lambda functions you will probably be fed this resource by the quote-unquote "google": https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-debugging.html
However, there are other ways to do it.
I personally use the public docker image from aws.
Here is an example of the docker image created for a specific use case of mine.
FROM public.ecr.aws/lambda/python:3.8
RUN yum -y install tar gzip zlib freetype-devel \
gcc \
ghostscript \
lcms2-devel \
libffi-devel \
libimagequant-devel \
.
enter code here
enter code here
and some more dependencies ....
&& yum clean all
COPY requirements.txt ./
RUN python3.8 -m pip install -r requirements.txt
# Replace Pillow with Pillow-SIMD to take advantage of AVX2
RUN pip uninstall -y pillow && CC="cc -mavx2" pip install -U --force-reinstall pillow-simd
COPY <handler>.py ./<handler>.py
# Set the CMD to your handler
ENTRYPOINT [ "python3.8","app5.py" ]
In your case, follow instructions for node and run the docker image locally. If it works, you can then continue with aws lambda creation/update.
I see that you also have a cron job, why not use the cron job to invoke this lambda function separately and not define it in you SAML?
There are a number of ways you can invoke a lambda function based on event. For example to invoke using cli: (For aws-cliv2)
make sure you configure awscli
# !/bin/bash
export AWS_PROFILE=<your aws profile>
export AWS_REGION=<aws region>
aws lambda invoke --function-name <function name> \
--cli-binary-format raw-in-base64-out \
--log-type Tail \
--payload <your json payload > \
<output filename>
Makes it loosely coupled.
Then you can use carlo's node cronjob suggestion to invoke is as many times you like, free of charge.
CodePudding user response:
In AWS SAM, The Schedule event source type creates a AWS::Events::Rule under the hood with the lambda as the target in a full fat cloudformation template.
There is no current way to emulate this locally.